How can values be extracted from a JSON using Python?
To extract values from JSON in Python, you can use the json module. First, use the json.loads() function to parse the JSON string into a Python object (usually a dictionary or list), and then access the desired value by key or index.
Here is an example:
import json
# JSON字符串
json_data = '{"name": "John", "age": 30, "city": "New York"}'
# 将JSON字符串解析为Python对象
data = json.loads(json_data)
# 获取键为"name"的值
name = data["name"]
print(name) # 输出:John
# 获取键为"age"的值
age = data["age"]
print(age) # 输出:30
# 获取键为"city"的值
city = data["city"]
print(city) # 输出:New York
If the JSON data is a list containing multiple objects, you can access each object using indexes.
import json
# JSON字符串
json_data = '[{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]'
# 将JSON字符串解析为Python对象
data = json.loads(json_data)
# 获取第一个对象的"name"键的值
name1 = data[0]["name"]
print(name1) # 输出:John
# 获取第二个对象的"age"键的值
age2 = data[1]["age"]
print(age2) # 输出:25
In the code above, the json.loads() function parses a JSON string into a list containing two dictionary objects, and then accesses the values of each object using indexes and keys.