Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping strings to multiple types for json objects?

Tags:

json

go

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"` } 
like image 288
Derek Avatar asked Aug 30 '13 06:08

Derek


1 Answers

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} 
like image 138
ANisus Avatar answered Sep 23 '22 09:09

ANisus