How to Flatten Nested JSON Structures in Go Using Custom UnmarshalJSON Functions?

Susan Sarandon
Release: 2024-10-27 08:04:02
Original
560 people have browsed it

How to Flatten Nested JSON Structures in Go Using Custom UnmarshalJSON Functions?

Flattening Nested JSON

Navigating complex JSON structures with multiple levels of nesting can be challenging in Go. When it becomes necessary to flatten these nested structures into a more streamlined format, custom solutions are often needed.

In the presented scenario, the task is to flatten a JSON response that contains a nested Social type with a further nested Facebook type. The goal is to eliminate the intermediate Facebook type and flatten its properties into the Social type.

Custom UnmarshalJSON Functions

To achieve this, we can utilize the power of Go's UnmarshalJSON function, which allows you to customize how JSON is decoded into a struct. Here's how to implement this for flattening nested JSON:

<code class="go">type Social struct {
    // ... existing properties ...
    FacebookLikes       uint32 `json:"-"`
    FacebookShares      uint32 `json:"-"`
    FacebookComments    uint32 `json:"-"`
    FacebookTotal       uint32 `json:"-"`
}

func (s *Social) UnmarshalJSON(data []byte) error {
    m := make(map[string]interface{})
    if err := json.Unmarshal(data, &m); err != nil {
        return err
    }

    m = Flatten(m)

    // Extract nested Facebook properties
    if fbMap, ok := m["Facebook"].(map[string]interface{}); ok {
        s.FacebookLikes = fbMap["FacebookLikes"].(uint32)
        s.FacebookShares = fbMap["FacebookShares"].(uint32)
        s.FacebookComments = fbMap["FacebookComments"].(uint32)
        s.FacebookTotal = fbMap["FacebookTotal"].(uint32)
    }

    return nil
}</code>
Copy after login

Flatten Helper Function

The Flatten helper function is responsible for removing nested maps and replacing them with dot-delimited keys:

<code class="go">func Flatten(m map[string]interface{}) map[string]interface{} {
    o := make(map[string]interface{})
    for k, v := range m {
        switch child := v.(type) {
        case map[string]interface{}:
            nm := Flatten(child)
            for nk, nv := range nm {
                o[k+"."+nk] = nv
            }
        default:
            o[k] = v
        }
    }
    return o
}</code>
Copy after login

Using this approach, the nested Facebook type is removed, and its properties are flattened into the Social type, resulting in a more concise and manageable data structure.

The above is the detailed content of How to Flatten Nested JSON Structures in Go Using Custom UnmarshalJSON Functions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!