以下是一个示例代码,展示了如何从JSON对象中按路径提取数据:
import json
def get_value_by_path(json_obj, path):
path_list = path.split('.')
current_obj = json_obj
for key in path_list:
if key.isdigit():
key = int(key)
current_obj = current_obj[key]
return current_obj
# 示例 JSON 对象
json_str = '''
{
"name": "John",
"age": 30,
"address": {
"street": "123 Street",
"city": "New York"
},
"hobbies": ["reading", "painting", "music"]
}
'''
# 将 JSON 字符串解析为 JSON 对象
json_obj = json.loads(json_str)
# 提取数据
name = get_value_by_path(json_obj, 'name')
age = get_value_by_path(json_obj, 'age')
street = get_value_by_path(json_obj, 'address.street')
city = get_value_by_path(json_obj, 'address.city')
first_hobby = get_value_by_path(json_obj, 'hobbies.0')
# 打印结果
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Street: {street}")
print(f"City: {city}")
print(f"First Hobby: {first_hobby}")
上述代码首先定义了一个get_value_by_path
函数,该函数接受一个JSON对象和路径作为参数,然后按照路径提取数据并返回结果。
接下来,我们将示例JSON字符串解析为JSON对象。然后,我们使用get_value_by_path
函数提取了姓名、年龄、街道、城市和第一个爱好的数据,并将结果打印出来。
注意,路径可以是包含嵌套层级和数组索引的字符串,使用.
分隔。在处理数字索引时,我们将其转换为整数类型。
希望这个示例能够帮助你理解如何按路径从JSON对象中提取数据。