首頁  >  文章  >  後端開發  >  如何使用 Go 中的自訂 UnmarshalJSON 函數將巢狀 JSON 資料展平為單級結構?

如何使用 Go 中的自訂 UnmarshalJSON 函數將巢狀 JSON 資料展平為單級結構?

Susan Sarandon
Susan Sarandon原創
2024-10-28 14:49:02295瀏覽

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

展平巢狀 JSON

將巢狀 JSON 資料展平為單級結構是資料處理中的常見任務。以下是如何使用自訂 UnmarshalJSON 函數在 Go 中實現此目的:

UnmarshalJSON 函數

自訂 UnmarshalJSON 函數允許 Go 結構體處理 JSON 資料的解組。這是使用UnmarshalJSON 實現更新的社交結構:

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

用法

使用更新的社交結構,您現在可以解組JSON 文件並將其展平:

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

此程式碼將輸出您想要的扁平JSON 結構,並將Facebook 欄位合併到頂層社交結構中。

以上是如何使用 Go 中的自訂 UnmarshalJSON 函數將巢狀 JSON 資料展平為單級結構?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn