1

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

1
  • I have a source struct, what does "Make sure the source json tag is in line." mean ? Commented Sep 10, 2017 at 17:09

2 Answers 2

2

You may define custom marshaller:

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

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

Sign up to request clarification or add additional context in comments.

Comments

0

Add this to your source:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.