thearnabsarkar commited on
Commit
fda7d57
·
verified ·
1 Parent(s): d797826

Upload json_semval/jsonpath_utils.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. json_semval/jsonpath_utils.py +65 -0
json_semval/jsonpath_utils.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, List, Tuple
4
+
5
+
6
+ def path_to_jsonpath(path_tokens: List[str]) -> str:
7
+ return "$" if not path_tokens else "$" + "".join(path_tokens)
8
+
9
+
10
+ def build_path_tokens(key_stack: List[str]) -> List[str]:
11
+ # keys as [".user", "[0]", ".name"]
12
+ return key_stack
13
+
14
+
15
+ def set_value_at_path(payload: Any, path_tokens: List[str], value: Any) -> Any:
16
+ node = payload
17
+ parents: List[Tuple[Any, str]] = []
18
+ for token in path_tokens[:-1]:
19
+ parents.append((node, token))
20
+ if token.startswith("["):
21
+ idx = int(token.strip("[]"))
22
+ node = node[idx]
23
+ else:
24
+ key = token[1:] if token.startswith(".") else token
25
+ node = node[key]
26
+ last = path_tokens[-1]
27
+ if last.startswith("["):
28
+ idx = int(last.strip("[]"))
29
+ node[idx] = value
30
+ else:
31
+ key = last[1:] if last.startswith(".") else last
32
+ node[key] = value
33
+ return payload
34
+
35
+
36
+ def get_value_at_path(payload: Any, path_tokens: List[str]) -> Any:
37
+ node = payload
38
+ for token in path_tokens:
39
+ if token.startswith("["):
40
+ idx = int(token.strip("[]"))
41
+ node = node[idx]
42
+ else:
43
+ key = token[1:] if token.startswith(".") else token
44
+ node = node[key]
45
+ return node
46
+
47
+
48
+ def delete_key_at_path(payload: Any, path_tokens: List[str]) -> Any:
49
+ node = payload
50
+ for token in path_tokens[:-1]:
51
+ if token.startswith("["):
52
+ idx = int(token.strip("[]"))
53
+ node = node[idx]
54
+ else:
55
+ key = token[1:] if token.startswith(".") else token
56
+ node = node[key]
57
+ last = path_tokens[-1]
58
+ if last.startswith("["):
59
+ idx = int(last.strip("[]"))
60
+ del node[idx]
61
+ else:
62
+ key = last[1:] if last.startswith(".") else last
63
+ if isinstance(node, dict) and key in node:
64
+ del node[key]
65
+ return payload