Home  >  Article  >  Backend Development  >  How to Flatten Nested JSON in Go?

How to Flatten Nested JSON in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-10-27 04:01:30894browse

How to Flatten Nested JSON in Go?

Flattening Nested JSON

You have a nested JSON response and want to flatten it to a single level, eliminating the nested Facebook type. To achieve this, you can utilize a custom UnmarshalJSON function. However, a simpler and more flexible solution is to use a flattening function.

Custom Flattening Function

<code class="go">// Flatten takes a map and returns a new one where nested maps are replaced
// by dot-delimited keys.
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>

Using the Flattening Function

In your Go code:

<code class="go">var jsonBlob = []byte(`[
    {"StumbleUpon":0,"Reddit":0,"Facebook":{"commentsbox_count":4691,"click_count":0,"total_count":298686,"comment_count":38955,"like_count":82902,"share_count":176829},"Delicious":0,"GooglePlusOne":275234,"Buzz":0,"Twitter":7346788,"Diggs":0,"Pinterest":40982,"LinkedIn":0}
]`)

var social []Social
err := json.Unmarshal(jsonBlob, &amp;social)
if err != nil {
    fmt.Println("error:", err)
}

for _, s := range social {
    socialMap := Flatten(s)
    fmt.Printf("%+v\n", socialMap)
}</code>

Example Output

With the flattened Social map, you will get:

map[StumbleUpon:0 Reddit:0 Facebook.commentsbox_count:4691 Facebook.click_count:0 Facebook.total_count:298686 Delicious:0 GooglePlusOne:275234 Buzz:0 LinkedIn:0 Facebook.comment_count:38955 Facebook.like_count:82902 Facebook.share_count:176829 Twitter:7346788 Diggs:0 Pinterest:40982]

This output shows the flattened Social map with all the Facebook fields accessible as `Facebook....

This approach provides a generic way to flatten JSON responses, eliminating the need for nested types.

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

Statement:
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