0

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?

2
  • the method described in the answer about unmarshalling into interface{} is indeed correct, but from experience, in complex json objects, it's a nightmare, and you are better off specifying the data structure in advance. Commented May 1, 2014 at 9:49
  • So, why exactly don't you want to specify the type? What do you mean by messy? Can't you simplify it? Commented May 6, 2014 at 2:51

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.