Ryan
Ryan

Reputation: 10131

Decoding json in golang without declaring type relationship?

I don't want to specify the type of my json since they are so messy and so complicated, I just want them to load into memory and I perform the lookup when needed.

It is easy with dynamic language such as python, e.g.

data = json.loads(str)
if "foo" in data:
   ...

How to do the same in go?

Upvotes: 0

Views: 222

Answers (2)

user7180
user7180

Reputation: 4096

Here's an example which seems easier to understand for me, I hope it works for you too: https://gobyexample.com/json . Look for the word "arbitrary"

Upvotes: 0

Paul Hankin
Paul Hankin

Reputation: 58369

You can unmarshal into an interface{} value to decode arbitrary JSON.

Taking the example from http://blog.golang.org/json-and-go

b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)
var f interface{}
if err := json.Unmarshal(b, &f); err != nil {
    ... handle error
}

You need to use a type switch to access data decoded in this way. For example:

age := f.(map[string)interface{})["Age"].(int)

Upvotes: 1

Related Questions