英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论