Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unmarshal JSON with unknown field name [duplicate]

Tags:

json

go

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?

like image 390
Andrew Avatar asked Nov 13 '16 01:11

Andrew


1 Answers

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)
}
like image 151
twotwotwo Avatar answered Oct 10 '22 00:10

twotwotwo