Last Updated: July 25, 2019
·
116K
· 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.

1 Response
Add your response

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 ·