无法将具有非字符串键的映射转换为 JSON 字符串。

huangapple go评论71阅读模式
英文:

failed to json.marshal map with non string keys

问题

我想将一个map[int]string转换为json,所以我认为json.Marshal()可以解决问题,但是它失败了,显示不支持类型map[int]string。但是,如果我使用键为字符串的map,它就可以正常工作。

在检查编组器代码后,发现有一个明确的检查,如果键不是字符串,则返回UnsupportedTypeError...

为什么我甚至不能使用原始类型作为键?如果JSON标准不允许非字符串键,那么json.Marshal不应该将原始类型转换为字符串并将其用作键吗?

英文:

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 ?

答案1

得分: 14

这是要翻译的内容:

这不是因为Go语言的原因,而是因为Json的原因:Json不支持除字符串以外的其他类型作为键。

看一下Json的语法:

pair
    string : value
string
    ""
    " chars "

完整的语法可以在Json网站上找到。

不幸的是,要将整数用作键,你必须事先将它们转换为字符串,例如使用strconv.Itoa:这不是json包的工作。

英文:

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.

huangapple
  • 本文由 发表于 2014年6月18日 19:41:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/24284612.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定