Skip to content

Commit b70b705

Browse files
authored
Create json_values_finder.py
1 parent 2ace4f7 commit b70b705

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

scripts/json_values_finder.py

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

0 commit comments

Comments
 (0)