json marshal struct array的一个属性

时间:2017-09-10 16:31:40

标签: go

所以我有一个struct Recipe数组,它包含一些属性,其中一个属性是struct Source,我想将整个数组转换为json但只转换为Recipe结构的Source属性

代码:https://play.golang.org/p/E71d4xzNM4

结果:

[
{
    "Id": 1,
    "Title": "Fine Peanutbutter",
    "Description": "The best peanutbutter in the world",
    "Source": {
        "Name": "Peter",
        "Address": "32121 Little Midge"
    },
    "Price": 49
},
{
    "Id": 2,
    "Title": "Fine Jelly",
    "Description": "The best Jelly in the world",
    "Source": {
        "Name": "Peter",
        "Address": "32121 Little Midge"
    },
    "Price": 39
}
]

通缉结果:

[
{
    "Name": "Peter",
    "Address": "32121 Little Midge"     
},
{
    "Name": "Peter",
    "Address": "32121 Little Midge"
}
]

如何在不循环遍历整个数组并创建新数组结构并在该数组上执行json marshal的情况下获得此结构

2 个答案:

答案 0 :(得分:2)

您可以定义自定义编组:

func (r Recipe) MarshalJSON() ([]byte, error) {
  return json.Marshal(r.Source)
}

https://play.golang.org/p/xLUAlMllGR

答案 1 :(得分:0)

将此添加到您的来源:

func (s Recipe) MarshalJSON() ([]byte, error) {
    return json.Marshal(s.Source)
}