4c2zig
Last Updated: September 18, 2018
·
62.95K
· davidpelaez

Decode top level JSON array into a slice of structs in golang

It's not uncommon for public JSON APIs to reply with top level arrays, instead of a full JSON object. If you want to convert that JSON array into a slice of structs with the items of the array, heres how you can do it:

package main

import "fmt"
import "encoding/json"

type PublicKey struct {
    Id int
    Key string
}

type KeysResponse struct {
    Collection []PublicKey
}

func main() {
    keysBody := []byte(`[{"id": 1,"key": "-"},{"id": 2,"key": "-"},{"id": 3,"key": "-"}]`)
    keys := make([]PublicKey,0)
    json.Unmarshal(keysBody, &keys)
    fmt.Printf("%#v", keys)
}

Same code in the playground: http://play.golang.org/p/CvwXURmSCY

Golang is not a very complicated language but has very poor documentation standards compared to more popular things, like Ruby or JS. I actually had to figure this out over ours of googling to find the answer here (in a code review from golang source!): https://codereview.appspot.com/154121/patch/9/10

Hope it helps.

2 Responses
Add your response

17304

You do not actually need to allocate a slice with make; it is enough to declare the variable. The KeysResponse type is also unnecessary for this example.

Here is the simplified playground: http://play.golang.org/p/8Bq07-2Ump

over 1 year ago ·
30719

To be great launch for the play online game http://www.lounge.belloflostsouls.net/member.php?61272-abhi32

4 months ago ·