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})
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 51单片机C语言数码管驱动单片机为AT89C52
  • ¥100 只改动本课件的 cal_portfolio_weight_series(decision_date), 跑完本课件。设计一个信息比率尽量高的策略。
  • ¥20 如何在visual studio 2022中添加ImageMagick库
  • ¥50 如何实现uniapp编译的微信小程序做可回溯视频
  • ¥15 求Houdini使用行家,付费。价格面议。
  • ¥15 前端高拍仪调用问题报错
  • ¥15 想用octave解决这个数学问题
  • ¥15 Centos新建的临时ip无法上网,如何解决?
  • ¥15 海康威视如何实现客户端软件对设备语音请求的处理。
  • ¥15 支付宝h5参数如何实现跳转