根据this conversion table,Python int在使用JSON模块进行序列化时会被写成JSON数字——正如我所期望和期望的那样.

我有一个具有整数键和整数值的字典:

>>> d = {1:2}
>>> type(d.items()[0][0])
<type 'int'>
>>> type(d.items()[0][1])
<type 'int'>

When I use the json module to serialize this to a JSON string, the value is written as a number, but the key is written as a string:

>>> json.dumps(d)
'{"1": 2}'

This isn't the behavior I want, and it seems particularly broken since it breaks json.dumps/json.loads round-tripping:

>>> d == json.loads(json.dumps(d))
False

为什么会发生这种情况,有没有办法强制将密钥写成一个数字?

推荐答案

原因很简单,JSON does not allow integer keys.

object
    {}
    { members } 
members
    pair
    pair , members
pair
    string : value  # Keys *must* be strings.

至于如何绕过这个限制,首先需要确保接收实现能够处理技术上无效的JSON.然后,您可以替换所有引号或使用自定义序列化程序.

Json相关问答推荐

仅在通过Jolt输入时才级联Json的值

在Go中,当字段可以根据其他字段具有不同的类型时,什么是正确的方法来卸载JSON?

Vega通孔信号中的动态梯度

Vegalite中分组条形图中的偏移量问题

如何使用GoFr返回XML响应?

处理输入数据并转换为更简单的格式-PowerBI

在深度嵌套数组中使用布尔属性的jq-select

Jolt - 如何比较 if else 条件的两个值

Jolt规范:将嵌套数组中的null元素移除

如何从条带订阅响应对象中正确获取 struct 项?

使用 JQ 从文件中删除重复的 JSON 块

如何使用 ConfigurationBuilder 解析现有的 json 字符串(不是文件)

使用基本身份验证通过 CURL 发布 JSON

为什么在我们有 json_encode 时使用 CJSON 编码

如何将任意 json 对象发布到 webapi

Jackson 的@JsonView、@JsonFilter 和 Spring

json.dumps 打乱了顺序

IE中Json响应下载(7~10)

字符串的 Gson 数组到 JsonArray

通过 JSON 发送 HTML 代码