How to access the values of JSON data in Python?
You can use the json.loads() function to convert a JSON string into a Python dictionary, and then access the corresponding value using the dictionary keys.
Here is an example code:
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(name, age, city)
Result output:
John 30 New York
If you need to access nested field values, you can use the corresponding keys to access the values in the nested dictionary. For example:
import json
# json字符串
json_str = '{"name": "John", "age": 30, "address": {"city": "New York", "street": "123 Main St"}}'
# 将json字符串转换为字典
data = json.loads(json_str)
# 读取嵌套字段值
name = data['name']
age = data['age']
city = data['address']['city']
street = data['address']['street']
print(name, age, city, street)
Output:
John 30 New York 123 Main St