Python 和 JSON
JSON 是用于存储数据的语法。
JSON 是使用 JavaScript.
将 JSON 导入 Python
Python 使用名为 json,调用它来操作 JSON.
import json
将 JSON 转换为 Python (解析 JSON)
您可以使用 json.loads() 读取 Python 中的 JSON 内容。
结果存储在 Python 字典中。
import json
x = '{ name”:patrik”, age”:25, city”:Paris”}'
# 解析器 x:
y = json.loads(x)
print(y[city”])
将 Python 对象转换为 JSON
您可以使用以下方法转换 Python 对象 json.dumps().
import json
# object
x = {name”: patrik”, age”: 25, city”: Paris”}
# 转换为 JSON:
y = json.dumps(x)
# 结果将是 JSON
print(y)
Python 对象可以转换为不同类型的 JSON:
- dict ->对象
- tuple ->数组
- string ->字符串
- list ->数组
- int ->编号
- float ->编号
- True ->true
- false ->false
- 无 ->null
美化 JSON)
要美化 JSON 格式,json.dumps() 具有易于读取结果的参数:
import json
x = {
name”: Adam”,
age”: 32.
single”: False,
children”: (Leo”,Arthur”),
car”: [
{model”: 雷诺”, year”: 2022},
]
}
print(json.dumps(x, indent=4))
Result:
{
name”: 亚当”,
年龄”: 32,
单身”: false,
孩子”: [
L\u00e9o”,
亚瑟”
],
汽车”: [
{
model”: 雷诺”,
year”: 2022
}
]
}
Sort result
您还可以使用参数 sort_keys:
json.dumps(x, indent=4, sort_keys=True)