在 Python 中获取 JSON 值,可以使用内置的 json 库。json库提供了一些函数来读取和解析 JSON 数据。
首先,我们需要将 JSON 字符串解析为 Python 对象。可以使用 json.loads() 函数将 JSON 字符串转换为 Python 字典或列表,或者使用 json.load() 函数从文件中读取 JSON 数据并将其转换为 Python 对象。例如:
import json
# JSON 字符串
json_str = '{"name": "John", "age": 30, "city": "New York"}'
# 将 JSON 字符串解析为 Python 字典
data = json.loads(json_str)
# 输出 Python 字典中的值
print(data["name"]) # 输出 John
print(data["age"]) # 输出 30
print(data["city"]) # 输出 New York
如果 JSON 数据来自文件,则可以使用 json.load() 函数,如下所示:
import json
# 从文件中读取 JSON 数据并解析为 Python 对象
with open("data.json", "r") as file:
data = json.load(file)
# 输出 Python 字典中的值
print(data["name"]) # 输出 John
print(data["age"]) # 输出 30
print(data["city"]) # 输出 New York
如果 JSON 数据中包含嵌套的对象或数组,可以使用相同的方法获取其值。例如,如果 JSON 数据如下所示:
"name": "John",
"age": 30,
"city": "New York",
"children": [
{"name": "Mary", "age": 5},
{"name": "Tom", "age": 8}
则可以使用以下代码获取嵌套的值:
import json
# JSON 字符串
json_str = '{"name": "John", "age": 30, "city": "New York", "children": [{"name": "Mary", "age": 5}, {"name": "Tom", "age": 8}]}'
# 将 JSON 字符串解析为 Python 字典
data = json.loads(json_str)
# 输出嵌套的值
print(data["children"][0]["name"]) # 输出 Mary
print(data["children"][1]["age"]) # 输出 8
希望这些信息能对您有所帮助。如果您还有任何问题,请随时提问。