0

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 Answer 1

4

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})
Sign up to request clarification or add additional context in comments.

1 Comment

You are awesome

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.