dongyuan2652 2014-06-22 21:53
浏览 45
已采纳

在Go中编码嵌套的JSON

I've had a lot of trouble finding an example of this. Most of the information on the internet is about decoding JSON.

I'd like to serialize some data into nested JSON, like for example:

{
  "item": {
      "title": "Items",
    "properties": [
      {
        "num": 1,
        "name": "Item 1"
      },
      {
        "num": 2,
        "name": "Item 2"
      }
    ]
  }
}

I know how to marshal data with a flat struct, but how do I put data into a struct that can be serialized with nesting?

http://play.golang.org/p/nDKmv1myTD

I found this tool that generates a struct from a JSON schema, but I don't understand how to get data into the sub structs.

http://mholt.github.io/json-to-go/

type Example struct {
    Item struct {
        Title string `json:"title"`
        Properties []struct {
            Num int `json:"num"`
            Name string `json:"name"`
        } `json:"properties"`
    } `json:"item"`
}
  • 写回答

1条回答 默认 最新

  • doukanzhuo4297 2014-06-22 22:47
    关注

    This tool you found is nice, but I would not use it. It makes it difficult to initialize the structs.

    Init example with your snippet: (http://play.golang.org/p/_Qw3Qp8XZh)

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type Example struct {
        Item struct {
            Title      string `json:"title"`
            Properties []struct {
                Num  int    `json:"num"`
                Name string `json:"name"`
            } `json:"properties"`
        } `json:"item"`
    }
    
    func main() {
        info := &Example{
            Item: struct {
                Title      string `json:"title"`
                Properties []struct {
                    Num  int    `json:"num"`
                    Name string `json:"name"`
                } `json:"properties"`
            }{
                Title: "title",
                Properties: []struct {
                    Num  int    `json:"num"`
                    Name string `json:"name"`
                }{
                    {Num: 0, Name: "name0"},
                    {Num: 1, Name: "name1"},
                },
            },
        }
    
        b, err := json.Marshal(info)
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Println(string(b))
    }
    

    Result (pretty printed):

    {
      "item": {
        "title": "title",
        "properties": [
          {
            "num": 0,
            "name": "name0"
          },
          {
            "num": 1,
            "name": "name1"
          }
        ]
      }
    }
    

    I think it is better to use named struct vs anonymous nested ones.

    Same example with named structs: http://play.golang.org/p/xm7BXxEGTC

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type Example struct {
        Item Item `json:"item"`
    }
    
    type Item struct {
        Title      string     `json:"title"`
        Properties []Property `json:"properties"`
    }
    
    type Property struct {
        Num  int    `json:"num"`
        Name string `json:"name"`
    }
    
    func main() {
        info := &Example{
            Item: Item{
                Title: "title",
                Properties: []Property{
                    {Num: 0, Name: "name0"},
                    {Num: 1, Name: "name1"},
                },
            },
        }
    
        b, err := json.Marshal(info)
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Println(string(b))
    }
    

    It is the exact same thing, but I find it more clear and easy to use.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?