dsafq2131321 2016-10-11 12:15
浏览 119
已采纳

如何在Golang中给Json数组一个标识符

I am trying to create a JSON array in Go with a struct using json.Marshall however I cant seem to get the desired result here is the slice of structs I am working with.

posts := []models.Post{
    models.Post{Id: 1,MediaUrl:"...", Title: "...", Slug: "...", ShortDescription : "...", Content : "..."},
    models.Post{Id: 2,MediaUrl:"...", Title: "...", Slug: "...", ShortDescription : "...", Content : "..."},
}

And I am trying to marshall it into a struct that looks like

{"posts":[{"Id": 1,...},{"Id": 2,...}]}

But I am stuck at

[{"Id":1,...},{"Id": 2,...}]

I dont know how to get the additional {"posts":..} around the json array. How do I add this additional identifier to the json array? Thanks

  • 写回答

1条回答 默认 最新

  • duancan7914 2016-10-11 12:18
    关注

    Wrap the slice with a struct to add the JSON object with "posts" field:

    data := struct { 
       Posts []models.Post `json:"posts"`
    }{
       Posts: posts
    }
    p, err := json.Marshal(&data)
    

    An alternative is to wrap the slice with a map:

    p, err := json.Marshal(map[string]interface{}{"posts": posts})
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 powerbuilder出现这样的报错
  • ¥15 h3.6m 人类行为预测论文复现
  • ¥50 wordpress项目注册报失败刷新后其实是成功状态,请求排查原因
  • ¥20 linxu服务器僵尸进程不释放,代码如何修改?
  • ¥15 pycharm激活不成功
  • ¥40 如果update 一个列名为参数的value
  • ¥15 基于51单片机的水位检测系统设计中LCD1602一直不显示
  • ¥15 OCS2安装出现问题,请大家给点意见
  • ¥15 ros小车启动launch文件报错
  • ¥15 vs2015到期想登陆但是登陆不上