6

I want to convert a map[int]string to json, so I thought json.Marshal() would do the trick, but it fails saying unsupported type map[int]string. But whereas if I use a map with key string it works fine.

http://play.golang.org/p/qhlS9Nt8qQ

Later on inspection of the marshaller code, there is an explicit check to see if the key is not string and returns UnsupportedTypeError...

Why can't I even use primitives as keys? If json standard doesn't allow non string keys, shouldn't json.Marshal convert the primitives to string and use them as keys ?

Sohail Shaikh
  • 215
  • 1
  • 4
  • 10
Vishnu
  • 4,377
  • 7
  • 26
  • 40
  • 2
    It states as much in the package docs: "Map values encode as JSON objects. The map's key type must be string; the object keys are used directly as map keys". http://golang.org/pkg/encoding/json/#Marshal – Intermernet Jun 18 '14 at 11:51

1 Answers1

14

It's not because of Go, but because of Json: Json does not support anything else than strings for keys.

Have a look a the grammar of Json:

pair
    string : value
string
    ""
    " chars "

The full grammar is available on the Json website.

Unfortunately, to use integers as keys, you must convert them to string beforehand, for instance using strconv.Itoa: it is not up to the json package to do this work.

julienc
  • 19,087
  • 17
  • 82
  • 82
  • 1
    Seems like the newer versions of go support non string keys. "Map values encode as JSON objects. The map's key type must either be a string, an integer type, or implement encoding.TextMarshaler." – Vishnu Mar 02 '18 at 01:38