Derek Derek - 1 year ago 33
JSON Question

Mapping strings to multiple types for json objects?

I want to create a map that I can transform into a json object such as

{
"a": "apple",
"b": 2
}


but golang specifies that the map be declare with types, so I can have map[string]string or map[string]int. How do I create a json object like the above?

Note: I won't know what data and/or types I need until runtime or when I need to create the json object. Therefore I can't just create an object like

type Foo struct {
A string `json:"a"`
B int `json:"b"`
}

Answer Source

You can always use interface{}to store any type. As the documentation in the encoding/json package says:

To unmarshal JSON into an interface value, Unmarshal unmarshals the JSON into the concrete value contained in the interface value. If the interface value is nil, that is, has no concrete value stored in it, Unmarshal stores one of these in the interface value:

bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null

Just do the following:

m := map[string]interface{}{"a":"apple", "b":2}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download