我发现,在运行下面的代码时,python的json模块(自2.6版开始包含)会将int字典键转换为字符串.

>>> import json
>>> releases = {1: "foo-v0.1"}
>>> json.dumps(releases)
'{"1": "foo-v0.1"}'

有没有简单的方法可以将密钥保留为int,而不需要在转储和加载时解析字符串.

Sub-question: Thanks for the answers. Seeing as json works as I feared, is there an easy way to convey key type by maybe parsing the output of dumps? Also I should note the code doing the dumping and the code downloading the json object from a server and loading it, are both written by me.

推荐答案

This is one of those subtle differences among various mapping collections that can bite you. JSON treats keys as strings; Python supports distinct keys differing only in type.

In Python (and apparently in Lua) the keys to a mapping (dictionary or table, respectively) are object references. In Python they must be immutable types, or they must be objects which implement a __hash__ method. (The Lua docs suggest that it automatically uses the object's ID as a hash/key even for mutable objects and relies on string interning to ensure that equivalent strings map to the same objects).

In Perl, Javascript, awk and many other languages the keys for hashes, associative arrays or whatever they're called for the given language, are strings (or "scalars" in Perl). In perl $foo{1}, $foo{1.0}, and $foo{"1"} are all references to the same mapping in %foo --- the key is evaluated as a scalar!

JSON started as a Javascript serialization technology. (JSON stands for JavaScript Object Notation.) Naturally it implements semantics for its mapping notation which are consistent with its mapping semantics.

如果序列化的两端都是Python,那么最好使用pickles.如果您真的需要将这些从JSON转换回原生Python对象,我想您有两个 Select .首先,如果字典查找失败,您可以try (try: ... except: ...)将任何键转换为数字.或者,如果您向另一端(JSON数据的序列化程序或生成器)添加代码,那么您可以让它对每个键值执行JSON序列化——将它们作为键列表提供.(然后,Python代码将首先迭代键列表,将它们实例化/反序列化为本机Python对象……然后使用这些对象从映射中访问值).

Json相关问答推荐

两种情况下过滤的JOLT规范

为什么terraform不缩小这个策略JSON?'

服务器不返回JSON

如何在使用GO时检测JSON中不需要的字段?

使用WSO2 JsonTransform Mediator对空值执行JsonExceptionUndeletedOperationException

Flutter -控制器问题-JSON API

创建Json嵌套文件 struct

在 python 中循环 JSON 数组

如何使用 SQL Server 将 json 存储为字符串的列分解/规范化为行和列?

Jolt 变换 - 如何用字段值重命名字段?

jq json - 按键名 Select

阅读 JSON 正文 Firebase 云函数

在循环中将变量添加到 bash 数组

解析 JSON API 响应

现代浏览器一次可以处理多少个 HTML 元素?

应该使用什么标头将 GZIP 压缩 JSON 从 Android 客户端发送到服务器?

使用 jq,将对象数组转换为具有命名键的对象

如何创建 JSON 对象 Node.js

如何使用 Serde 反序列化带有自定义函数的可选字段?

处理 HTTP 请求正文中的可选 JSON 字段