Search code examples
jsongounmarshalling

Parse JSON response using array of struct with no leading keys in Go


Normally in Go, I would use the following struct:

type Inner struct {
    Key1 string `json:"Key1"`
    Key2 int32  `json:"Key2"`
}
    
type Outer struct {
    Outer []Outer `json:"Outer"`
}

To Decode the following JSON into:

 {"Outer":[{"Key1" : "Value1", "Key2" : 2}, ...]}

I'm unable to figure out what struct to use for the following JSON:

[{"Key1" : "Value1", "Key2" : 2}, ...]

Due to the fact that I have no JSON key for the outer object. How do you handle this situation?


Solution

  • Parse a JSON array of objects to a Go slice of structs.

    data := []byte(`[{"Key1":"Value1", "Key2":2}, {"Key1":"Value3", "Key2":4}]`)
    
    type Inner struct {
        Key1 string `json:"Key1"`
        Key2 int32  `json:"Key2"`
    }
    var v []Inner // <--- slice of struct
    
    err := json.Unmarshal(data, &v)
    if err != nil {
        log.Fatal(err)
    }
    for _, e := range v {
        fmt.Println(e)
    }
    

    Run it on the PlayGround.

    See the Unmarshal for documentation for information on the relationship between JSON values to Go types.