首页  >  文章  >  后端开发  >  我们如何在 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