Mapping strings to multiple types for json objects?

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}

To respond to the comments, I think it is easier to add type definitions for Map and Slice, then you don't have to worry about complex literal declarations:

package main
import "fmt"

type Map map[string]interface{}
type Slice []interface{}

func main() {
   m := Map{
      "a": "apple",
      "b": 2,
      "c": Slice{"foo", 2, "bar", false, Map{"baz": "bat", "moreFoo": 7}},
   }
   fmt.Println(m)
}

https://golang.org/ref/spec#Type_definitions

Tags:

Json

Go