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 相同型号电脑与配置,发现主板有一台貌似缺少了好多元器件似的,会影响稳定性和使用寿命吗?
    • ¥15 要求编写稀疏矩阵A的转置矩阵的算法
    • ¥15 编写满足以下要求的停车场管理程序,设停车场只有一个可停放n辆车的狭窄通道且只有一个大门可供车辆进出。
    • ¥20 powerbulider 导入excel文件,显示不完整
    • ¥15 用keil调试程序保证结果进行led相关闪烁
    • ¥15 paddle训练自己的数据loss降不下去
    • ¥20 用matlab的pdetool解决以下三个问题
    • ¥15 单个福来轮的平衡与侧向滑动是如何做到的?
    • ¥15 嵌入式Linux固件,能直接告诉我crc32校验的区域在哪不,内核的校验我已经找到了,uboot没有
    • ¥20 h3c静态路要求有详细过程