你可以使用json.loads()
函数将json字符串转换为python字典,然后使用字典的键来访问相应的值。
下面是一个示例代码:
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)
输出结果:
John 30 New York
如果你要读取嵌套的字段值,可以使用相应的键来访问嵌套字典的值。例如:
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)
输出结果:
John 30 New York 123 Main St