首页  >  文章  >  后端开发  >  如何使用 Go 中的自定义 UnmarshalJSON 函数将嵌套 JSON 数据展平为单级结构?

如何使用 Go 中的自定义 UnmarshalJSON 函数将嵌套 JSON 数据展平为单级结构?

Susan Sarandon
Susan Sarandon原创
2024-10-28 14:49:02288浏览

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