-1

Currently I have stored in my database json objects as string. I want to pass them to a map to be able to consult any field as:

Mymap["Name"]
Mymap["Age"]
..

Let's say that my string would be something like:

'{"Name":["zero"],"Age":"10"}'

I don't know the structure of the data, so that Json can have many fields as required and also many levels of nestings (but I am worried more about to get at least the first level)

0

1 Answer 1

3

If you're dealing with a json object of arbitrary structure you can use a map of interfaces as the type to unmarshal it into.

map[string]interface{}

The encoding/json package will nicely unmarshal the json object into it, nested or not.

This, while very flexible, has an obvious downside, the types of the map's values are unknown and so to do anything useful with them you'll have to use a type assertion or type switch.

v, ok := m["key"].(Type)

https://play.golang.org/p/wM0gkU1g5G

Sign up to request clarification or add additional context in comments.

2 Comments

Well, you got me there ;). I'll fix the answer.
@zerkms Thanks for pointing it out and allowing me to correct myself.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.