Andrew Andrew - 25 days ago 8
JSON Question

Unmarshal JSON with unknown field name

I have a JSON object, something like this:

{
"randomstring": {
"everything": "here",
"is": "known"
}
}


Basically everything inside the
randomstring
object is known, I can model that, but the randomstring itself is random. I know what it's going to be, but it's different every time. Basically all the data I need is in the randomstring object. How could I parse this kind of JSON to get the data?

Answer

Use a map where the key type is string and the value type is a struct with the fields you want, like in this example on the Playground and below:

package main

import (
    "encoding/json"
    "fmt"
    "log"
)

type Item struct{ X int }

var x = []byte(`{
    "zbqnx": {"x": 3}
}`)

func main() {
    m := map[string]Item{}
    err := json.Unmarshal(x, &m)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(m)
}