在Go中编码嵌套的JSON

时间:2014-06-22 21:53:17

标签: json serialization encoding go

我找到一个这方面的例子很困难。互联网上的大部分信息都是关于解码JSON。

我想将一些数据序列化为嵌套的JSON,例如:

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

我知道如何使用平面结构封送数据,但是如何将数据放入可以使用嵌套序列化的结构中?

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

我发现这个工具可以从JSON模式生成结构,但我不了解如何将数据导入子结构。

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 个答案:

答案 0 :(得分:9)

你找到的这个工具很好,但我不会用它。这使得初始化结构变得很困难。

使用您的代码段的初始示例:(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))
}

结果(漂亮印刷):

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

我认为使用命名结构与匿名嵌套结构更好。

与命名结构相同的示例: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))
}

完全相同,但我发现它更清晰易用。