Skip to content

Commit 4652c0c

Browse files
authored
Create json_value_finder.py
1 parent 33ec0cf commit 4652c0c

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

scripts/json_value_finder.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
def find_path(d, target, path=None):
2+
if path is None:
3+
path = []
4+
5+
if isinstance(d, dict):
6+
for k, v in d.items():
7+
new_path = path + [k]
8+
if v == target:
9+
return new_path
10+
elif isinstance(v, (dict, list)):
11+
result = find_path(v, target, new_path)
12+
if result:
13+
return result
14+
elif isinstance(d, list):
15+
for i, v in enumerate(d):
16+
new_path = path + [i]
17+
if v == target:
18+
return new_path
19+
elif isinstance(v, (dict, list)):
20+
result = find_path(v, target, new_path)
21+
if result:
22+
return result
23+
return None
24+
25+
import json
26+
def read_json(file_name:str='db.json')->dict:
27+
with open(file_name, 'r', encoding='utf-8') as file:
28+
data = json.load(file)
29+
return data
30+
31+
if __name__ == "__main__":
32+
data = {
33+
"key1": "value1",
34+
"key2": {
35+
"key3": "value3",
36+
"key4": "value4"
37+
},
38+
"key5": [
39+
"value5",
40+
"value6",
41+
{"key6": "value7"}
42+
]
43+
}
44+
45+
result_path = find_path(data, "value7")
46+
print(result_path) # Output: ['key5', 2, 'key6']

0 commit comments

Comments
 (0)