本文介绍了无法使用非字符串键的json.marshal映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 map [int] string 转换为 json ,所以我认为 json.Marshal()可以做到这一点,但是它失败时说不支持的类型 map [int] string 。但是,如果我使用 map 键字符串,它可以正常工作。



稍后在检查编组代码时,显式检查密钥是否不是字符串,并返回 UnsupportedTypeError ...



为什么我甚至不能使用基元作为键?如果json标准不允许非字符串键,不应该 json.Marshal 将原语转换为字符串并将它们用作键?




看看Json的语法:

  pair 
string:value
string

chars

完整的语法可在。



不幸的是,要使用整数作为键,必须将它们转换为例如使用 strconv.Itoa :它不能达到 json 包来完成这项工作。 / p>

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 ?

解决方案

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.

这篇关于无法使用非字符串键的json.marshal映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:03