首頁  >  文章  >  後端開發  >  我們如何在 Go 中展平嵌套的 JSON 回應?

我們如何在 Go 中展平嵌套的 JSON 回應?

Patricia Arquette
Patricia Arquette原創
2024-10-27 16:22:29393瀏覽

How Can We Flatten Nested JSON Responses in Go?

在 Go 中扁平化巢狀 JSON 回應

處理 JSON 資料時,常會遇到巢狀結構。雖然這種分層組織可以提供清晰度,但也可能使有效存取特定資料變得困難。為了簡化此過程,扁平化巢狀 JSON 回應可能會很有幫助。

實作自訂 UnmarshalJSON

要在 Go 中扁平化巢狀 JSON 回應,一種方法是為所需的結構類型實作自訂 UnmarshalJSON 函數。此函數可讓您處理解群組過程並相應地轉換資料。

在提供的Go 程式碼中,Social 結構代表所需的扁平化格式:

<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"`
    FacebookLikes uint32 `json:"??some_magical_nested_address??"`
    FacebookShares uint32 `json:"??some_magical_nested_address??"`
    FacebookComments uint32 `json:"??some_magical_nested_address??"`
    FacebookTotal uint32 `json:"??some_magical_nested_address??"`
}</code>

扁平化巢狀的Facebook數據,您可以如下實作UnmarshalJSON 函數:

<code class="go">func (s *Social) UnmarshalJSON(data []byte) error {
    type SocialTemp struct {
        GooglePlusPlusOnes  uint32 `json:"GooglePlusOne"`
        TwitterTweets       uint32 `json:"Twitter"`
        LinkedinShares      uint32 `json:"LinkedIn"`
        PinterestPins       uint32 `json:"Pinterest"`
        StumbleuponStumbles uint32 `json:"StumbleUpon"`
        DeliciousBookmarks  uint32 `json:"Delicious"`
        Facebook           struct {
            FacebookLikes    uint32 `json:"like_count"`
            FacebookShares   uint32 `json:"share_count"`
            FacebookComments uint32 `json:"comment_count"`
            FacebookTotal    uint32 `json:"total_count"`
        } `json:"Facebook"`
    }
    
    var temp SocialTemp
    if err := json.Unmarshal(data, &temp); err != nil {
        return err
    }
    
    *s = Social{
        GooglePlusPlusOnes:  temp.GooglePlusPlusOnes,
        TwitterTweets:       temp.TwitterTweets,
        LinkedinShares:      temp.LinkedinShares,
        PinterestPins:       temp.PinterestPins,
        StumbleuponStumbles: temp.StumbleuponStumbles,
        DeliciousBookmarks:  temp.DeliciousBookmarks,
        FacebookLikes:        temp.Facebook.FacebookLikes,
        FacebookShares:       temp.Facebook.FacebookShares,
        FacebookComments:    temp.Facebook.FacebookComments,
        FacebookTotal:       temp.Facebook.FacebookTotal,
    }
    return nil
}</code>

此實作使用臨時結構(SocialTemp) 來最初解組資料。然後,它在返回之前將扁平化的值提取到所需的社交結構中。

使用實用函數(建議)

另一種方法是利用答案中提供的實用函數,例如Flatten:

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

您可以應用此實用函數:

<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 flatJson = Flatten(json.Unmarshal(jsonBlob))</code>

這將產生包含所需資料結構的扁平化地圖。

以上是我們如何在 Go 中展平嵌套的 JSON 回應?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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