温馨提示×

python如何获取json中的某个值

小亿
113
2023-09-04 13:26:27
栏目: 编程语言

在Python中,可以使用json模块来解析JSON字符串。可以通过将JSON字符串转换为字典或列表的形式,然后使用索引或键名来获取JSON中的特定值。

以下是一个示例代码,展示了如何获取JSON中的某个值:

import json
# JSON字符串
json_str = '{"name": "John", "age": 30, "city": "New York"}'
# 将JSON字符串解析为字典
data = json.loads(json_str)
# 获取特定键的值
name = data['name']
age = data['age']
city = data['city']
# 打印结果
print(f'Name: {name}')
print(f'Age: {age}')
print(f'City: {city}')

输出结果:

Name: John
Age: 30
City: New York

在上述示例中,首先将JSON字符串json_str使用json.loads()函数解析为字典形式的数据。然后,可以通过键名获取字典中的特定值。

0