python - 读取 JSON 并将键转换为 int

标签 python json dictionary

众所周知,json 将 dict 的整数键转换为字符串:

import json
print json.dumps({1: [2.5, 2.5, 2.5], 2: [3, 3, 3, 3]})
# {"1": [2.5, 2.5, 2.5], "2": [3, 3, 3, 3]}

加载回来时恢复整数键最干净的方法是什么?

d = json.loads('{"1": [2.5, 2.5, 2.5], "2": [3, 3, 3, 3]}')
print d
# {u'1': [2.5, 2.5, 2.5], u'2': [3, 3, 3, 3]}

我在想:

d = {int(k): d[k] for k in d}

但是有没有更简洁的方法来处理带有 JSON/Python 整数键的字典,而不需要事后进行键转换?

最佳答案

使用object_hook定义自定义函数并执行操作:

import json

def keystoint(x):
    return {int(k): v for k, v in x.items()}

j = json.dumps({1: [2.5, 2.5, 2.5], 2: [3, 3, 3, 3]})
# {"1": [2.5, 2.5, 2.5], "2": [3, 3, 3, 3]}

print(json.loads(j, object_hook=keystoint))
# {1: [2.5, 2.5, 2.5], 2: [3, 3, 3, 3]}

来自 docs :

object_hook is an optional function that will be called with the result of any object literal decoded (a dict). The return value of object_hook will be used instead of the dict.


或者,您也可以使用 object_pairs_hook 来迭代对并保存 .items() 调用(感谢@chepner):

import json

def keystoint(x):
    return {int(k): v for k, v in x}

j = json.dumps({1: [2.5, 2.5, 2.5], 2: [3, 3, 3, 3]})
# {"1": [2.5, 2.5, 2.5], "2": [3, 3, 3, 3]}

print(json.loads(j, object_pairs_hook=keystoint))
# {1: [2.5, 2.5, 2.5], 2: [3, 3, 3, 3]}

来自文档:

object_pairs_hook is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict.

关于python - 读取 JSON 并将键转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53050408/

相关文章:

python - 如何在字典中查找共享相同键的值?

python - 将 mysql 连接到 django

python - 如何改进在 Python 中移动所有不包含特定日期的文件?

iphone - 将特定符号从 json 转换为普通 utf-8

具有一个强制性属性和至少另一个未键入的 json 模式检查

c# - Dictionary.Keys 返回的 KeyCollection 的操作速度有多快? (。网)

java - 无法在其他方法中检索 HashMap 输入

Python 'different_locale' 错误的区域设置转换

python - 在 Internet Explorer 的 Jupyter Notebook 中不显示 Folium 热图

iOS:使用 AFNetworking 解析 JSON 并检索特定信息?