为什么在使用json.dumps时python dict的int键变成字符串?

根据此转换表,使用JSON模块进行序列化时,Python int会以JSON数字的形式写入-正如我所期望和期望的那样。


我有一本带有整数键和整数值的字典:


>>> d = {1:2}

>>> type(d.items()[0][0])

<type 'int'>

>>> type(d.items()[0][1])

<type 'int'>

当我使用json模块将其序列化为JSON字符串时,该值被写为数字,但密钥被写为字符串:


>>> json.dumps(d)

'{"1": 2}'

这不是我想要的行为,它似乎特别损坏,因为它使json.dumps / json.loads往返中断了:


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

False

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


守候你守候我
浏览 1572回答 3
3回答

侃侃无极

原因很简单,JSON不允许整数键。object&nbsp; &nbsp; {}&nbsp; &nbsp; { members }&nbsp;members&nbsp; &nbsp; pair&nbsp; &nbsp; pair , memberspair&nbsp; &nbsp; string : value&nbsp; # Keys *must* be strings.关于如何解决此限制-您首先需要确保接收实现可以处理技术上无效的JSON。然后,您可以替换所有的引号或使用自定义的序列化程序。

鸿蒙传说

如果可能,此函数将递归地将所有字符串键转换为int键。如果不可能,则密钥类型将保持不变。我在下面稍微调整了JLT的示例。使用我的一些巨大的嵌套字典,这些代码使字典的大小发生了变化,但有一个例外。无论如何,归功于JLT!def pythonify(json_data):&nbsp; &nbsp; correctedDict = {}&nbsp; &nbsp; for key, value in json_data.items():&nbsp; &nbsp; &nbsp; &nbsp; if isinstance(value, list):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value = [pythonify(item) if isinstance(item, dict) else item for item in value]&nbsp; &nbsp; &nbsp; &nbsp; elif isinstance(value, dict):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value = pythonify(value)&nbsp; &nbsp; &nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; key = int(key)&nbsp; &nbsp; &nbsp; &nbsp; except Exception as ex:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pass&nbsp; &nbsp; &nbsp; &nbsp; correctedDict[key] = value&nbsp; &nbsp; return correctedDict

MM们

如果确实需要,可以使用以下命令检查是否可以再次将其转换为整数的键:def pythonify(json_data):&nbsp; &nbsp; for key, value in json_data.iteritems():&nbsp; &nbsp; &nbsp; &nbsp; if isinstance(value, list):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value = [ pythonify(item) if isinstance(item, dict) else item for item in value ]&nbsp; &nbsp; &nbsp; &nbsp; elif isinstance(value, dict):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value = pythonify(value)&nbsp; &nbsp; &nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; newkey = int(key)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; del json_data[key]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; key = newkey&nbsp; &nbsp; &nbsp; &nbsp; except TypeError:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pass&nbsp; &nbsp; &nbsp; &nbsp; json_data[key] = value&nbsp; &nbsp; return json_data
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python