有时候,我们拿到一个JSON数据的时候,会难以看出其逻辑层次结构。
这时候就需要我们进行代码解析了。
代码:
import json
def find_json_value(data_json, value, path=""):
if isinstance(data_json, dict):
for k, v in data_json.items():
new_path = f"{path}.{k}" if path else k
if v == value:
print(f"Value {value} found at path : {new_path}")
find_json_value(v, value, new_path)
elif isinstance(data_json, list):
for i, v in enumerate(data_json):
new_path = f"{path}[{i}]"
find_json_value(v, value, new_path)
def __test_find_json_value():
data_json = {
"name": "wtl",
"age": 31,
"city": "China",
"author": {
"email": "1050100468@qq.com",
"github": "https://github.com"
}
}
find_json_value(data_json, "1050100468@qq.com", "")
if __name__ == '__main__':
__test_find_json_value()