首页 > 解决方案 > 在 Python 中加载 JSON 并通过内部变量引用

问题描述

我有 JSON

[{"id": 1, "title": "ble", "description": "ble", "done": true}, {"id":2, "title": "2", "description": "2", "done": true}]

我想将它加载到 Python 3 字典中,然后我可以通过idJSON 引用它,就像print(json[2])打印一个项目一样。

标签: pythonjsonpython-3.x

解决方案


使用内置json包:https ://docs.python.org/3/library/json.html

import json

# some JSON:
stringifiedJSON = '[{"id": 1, "title": "ble", "description": "ble", "done": true}, {"id":2, "title": "2", "description": "2", "done": true}]'

# parse x:
parsedJSON = json.loads(stringifiedJSON) # a dict representing the JSON

# access specific field
print(parsedJson[1])

输出: >>> { "id":2, "title":"2", "description":"2", "done":true }

请注意,无法访问2您提供的 JSON 字符串示例中的键,因为它是一个只有 2 个元素的数组(索引从零开始)。


推荐阅读