你可以使用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