draxq02664 2014-06-18 11:41
浏览 103
已采纳

无法使用非字符串键对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条回答 默认 最新

  • donglikuang8145 2014-06-18 11:45
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动