Golang Json编组

时间:2017-12-01 02:50:13

标签: json go marshalling unmarshalling

type Status struct {
 slug  string  `json:"slug"` 
}

type Instance struct {
  Slug   string                   `json:"slug"`
  Stat   map[string]*Status       `json:"status"`
 }

此次Json响应已收到API调用:

    [ {
    "status": {
      "stop": false,
      "traffic": true,
      "label": null,
      "dead": true,
      "slug": "up",
    }, 
    "slug": "instances_raw",
    "started_at": "15120736198",
    "replacement": null
    },

    {
    "status": {
      "stop": false,
      "traffic": true,
      "label": null,
      "dead": true,
      "slug": "down",
     },
    "slug": "instance_raw2",
    "started_at": "1512073194",
    "replacement": null
   }
  ]

我正在尝试将json编组到上面的结构中但遇到问题:

instances := make([]Instance, 0)
res := api call return above json
body, _ := ioutil.ReadAll(res.Body)
json.Unmarshal(body, &instances)
fmt.Println("I am struct %s",instances)

它正在编组:

I am struct %s [{ map[stop:0xc42018e1b0 dead:0xc42018e1e0 label:<nil> running:0xc42018e220 down:0xc42018e150 traffic:0xc42018e180]}]

有人可以帮我弄清楚为什么它不像我期待的那样编组吗?

预期的编组:

[{instances_raw map[slug:up]} {instances_raw2 map[slug:down]}] 

1 个答案:

答案 0 :(得分:2)

结构与数据结构不匹配。也许你想要这个:

type Status struct {
    Slug string `json:"slug"`
}

type Instance struct {
    Slug string `json:"slug"`
    Stat Status `json:"status"`
}

输出:[{instances_raw {up}} {instance_raw2 {down}}]

defining methods

或者这个:

type Instance struct {
    Slug string `json:"slug"`
    Stat map[string]interface{} `json:"status"`
}

输出:[{instances_raw map [label:dead:true slug:up stop:false traffic:true]} {instance_raw2 map [slug:down stop:false traffic:true label:dead:true]}]

run it on the plaground

始终检查错误。上面的示例JSON无效,json.Unmarshal函数报告此错误。