要按照列表中的数字/顺序在JSON对象中查找元素,可以使用以下代码示例解决:
import json
def find_element_in_json(json_obj, path):
"""
在JSON对象中按照路径查找元素
:param json_obj: JSON对象
:param path: 路径,由数字/顺序组成的列表
:return: 查找到的元素,若未找到则返回None
"""
current_obj = json_obj
for key in path:
if isinstance(current_obj, list) and isinstance(key, int) and key < len(current_obj):
current_obj = current_obj[key]
elif isinstance(current_obj, dict) and key in current_obj:
current_obj = current_obj[key]
else:
return None
return current_obj
# 示例JSON对象
json_str = '''
{
"name": "John",
"age": 30,
"languages": {
"english": ["fluent", "native"],
"french": "basic"
},
"hobbies": ["reading", "coding", "swimming"]
}
'''
# 解析JSON字符串
json_obj = json.loads(json_str)
# 要查找的路径
path = [ "languages", "english", 1 ]
# 在JSON对象中查找元素
result = find_element_in_json(json_obj, path)
# 输出结果
print(result)
运行以上代码,将输出 native
。这是因为根据给定的路径 [ "languages", "english", 1 ]
,在JSON对象中找到了对应的元素。