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.

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

报告相同问题?

悬赏问题

  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端