zbparse/flask_app/main/json提取.py

29 lines
860 B
Python
Raw Normal View History

2024-08-29 16:37:09 +08:00
import json
def search_key_in_json(file_path, search_key):
with open(file_path, 'r', encoding='utf-8') as file:
data = json.load(file)
# 递归函数查找键
def recursive_search(data, key):
if key in data:
return key, data[key]
for k, v in data.items():
if isinstance(v, dict):
result = recursive_search(v, key)
if result:
return result
return None
result = recursive_search(data, search_key)
if result:
return f"{result[0]} : {result[1]}"
else:
return f"{search_key} : /"
# 用法示例
file_path = 'C:/Users/Administrator/Downloads/truncate_output2.json' # 替换为你的 JSON 文件路径
search_key = '多标段投标' # 替换为你想搜索的键
print(search_key_in_json(file_path, search_key))