Home  >  Article  >  Backend Development  >  How can I flatten nested JSON data into a single level structure using custom UnmarshalJSON functions in Go?

How can I flatten nested JSON data into a single level structure using custom UnmarshalJSON functions in Go?

Susan Sarandon
Susan SarandonOriginal
2024-10-28 14:49:02288browse

How can I flatten nested JSON data into a single level structure using custom UnmarshalJSON functions in Go?

Flattening Nested JSON

Flattening nested JSON data into a single level structure is a common task in data processing. Here's how you can achieve this in Go using a custom UnmarshalJSON function:

UnmarshalJSON Function

Custom UnmarshalJSON functions allow Go structs to handle the unmarshalling of JSON data. Here's your updated Social struct with the UnmarshalJSON implementation:

<code class="go">type Social struct {
    GooglePlusPlusOnes  uint32 `Social:"GooglePlusOne"`
    TwitterTweets       uint32 `json:"Twitter"`
    LinkedinShares      uint32 `json:"LinkedIn"`
    PinterestPins       uint32 `json:"Pinterest"`
    StumbleuponStumbles uint32 `json:"StumbleUpon"`
    DeliciousBookmarks  uint32 `json:"Delicious"`

    // Custom unmarshalling for the Facebook fields
    FacebookLikes       uint32 `json:"-"`
    FacebookShares      uint32 `json:"-"`
    FacebookComments    uint32 `json:"-"`
    FacebookTotal       uint32 `json:"-"`
}

// UnmarshalJSON implements the Unmarshaler interface for custom JSON unmarshalling
func (s *Social) UnmarshalJSON(data []byte) error {
    type FacebookAlias Facebook
    aux := &struct {
        Facebook FacebookAlias `json:"Facebook"`
    }{}

    if err := json.Unmarshal(data, aux); err != nil {
        return err
    }

    s.FacebookLikes = aux.Facebook.FacebookLikes
    s.FacebookShares = aux.Facebook.FacebookShares
    s.FacebookComments = aux.Facebook.FacebookComments
    s.FacebookTotal = aux.Facebook.FacebookTotal
    return nil
}</code>

Usage

With the updated Social struct, you can now unmarshal your JSON document and flatten it:

<code class="go">package main

import (
    "encoding/json"
    "fmt"
)

type Social struct {
    // ... (same as before)
}

func (s *Social) UnmarshalJSON(data []byte) error { // ... (same as before) }

func main() {
    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, &social)
    if err != nil {
        fmt.Println("error:", err)
    }
    fmt.Printf("%+v", social)
}</code>

This code will output your desired flattened JSON structure, with Facebook fields merged into the top-level Social struct.

The above is the detailed content of How can I flatten nested JSON data into a single level structure using custom UnmarshalJSON functions 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