You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
39 lines
1.6 KiB
39 lines
1.6 KiB
import json
|
|
|
|
# 假设你的 JSON 文件路径是 'data.json'
|
|
file_path = '../JSON/16.json'
|
|
|
|
# 读取 JSON 文件
|
|
with open(file_path, 'r', encoding='utf-8') as file:
|
|
modelData = json.load(file)
|
|
|
|
|
|
# 递归函数,用于遍历 JSON 对象
|
|
def find_and_print_path(obj, target_value, path=""):
|
|
if isinstance(obj, dict):
|
|
for key, value in obj.items():
|
|
# 构建当前属性的完整路径
|
|
current_path = f"{path}/{key}" if path else key
|
|
# 如果当前值是字典或列表,继续递归遍历
|
|
if isinstance(value, (dict, list)):
|
|
find_and_print_path(value, target_value, current_path)
|
|
# 如果当前值是字符串,并且与目标值匹配,打印路径
|
|
elif isinstance(value, str) and value == target_value:
|
|
print(f"Found1 at: {current_path}")
|
|
elif isinstance(obj, list):
|
|
for index, item in enumerate(obj):
|
|
# 构建当前属性的完整路径
|
|
current_path = f"{path}/{index}" if path else str(index)
|
|
# 如果当前元素是字典或列表,继续递归遍历
|
|
if isinstance(item, (dict, list)):
|
|
find_and_print_path(item, target_value, current_path)
|
|
# 如果当前元素是字符串,并且与目标值匹配,打印路径
|
|
elif isinstance(item, str) and item == target_value:
|
|
print(f"Found2 at: {current_path}")
|
|
|
|
if __name__ == '__main__':
|
|
path_str=''
|
|
# 调用函数并传入 JSON 数据和目标值
|
|
img_name = "819ed9ad42992cabe0c17023ba4a58b1 (3).jpg"
|
|
find_and_print_path(modelData, img_name)
|