json marshal结构数组的一个属性 [英] json marshal one property of struct array

查看:770
本文介绍了json marshal结构数组的一个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

结果:

  [
{
Id:1,
标题:精美的花生酱,
描述:世界上最好的花生酱,
来源:{
Name:Peter,
Address:32121 Little Midge
},
价格:49
},
{
Id:2,
标题:美好的果冻,
描述:世界上最好的果冻,
来源:{
Name:Peter,
Address:32121 Little Midge
},
Price:39
}
]

通缉结果:

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

我怎样才能得到这个没有循环遍历整个数组,并创建一个新的数组结构,并对其做一个json元帅

<您可以定义自定义编组器:

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

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


So I have an array of struct Recipe it contains some properties and one of the properties is the struct Source, I want to convert the entire array to json but only the Source property of the Recipe struct

Code: https://play.golang.org/p/E71d4xzNM4

Result:

[
{
    "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
}
]

Wanted Result:

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

How do I get this without looping through the entire array and creating a new array struct and doing a json marshal on that one

解决方案

You may define custom marshaller:

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

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

这篇关于json marshal结构数组的一个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆