File size: 1,928 Bytes
fda7d57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
from __future__ import annotations

from typing import Any, List, Tuple


def path_to_jsonpath(path_tokens: List[str]) -> str:
    return "$" if not path_tokens else "$" + "".join(path_tokens)


def build_path_tokens(key_stack: List[str]) -> List[str]:
    # keys as [".user", "[0]", ".name"]
    return key_stack


def set_value_at_path(payload: Any, path_tokens: List[str], value: Any) -> Any:
    node = payload
    parents: List[Tuple[Any, str]] = []
    for token in path_tokens[:-1]:
        parents.append((node, token))
        if token.startswith("["):
            idx = int(token.strip("[]"))
            node = node[idx]
        else:
            key = token[1:] if token.startswith(".") else token
            node = node[key]
    last = path_tokens[-1]
    if last.startswith("["):
        idx = int(last.strip("[]"))
        node[idx] = value
    else:
        key = last[1:] if last.startswith(".") else last
        node[key] = value
    return payload


def get_value_at_path(payload: Any, path_tokens: List[str]) -> Any:
    node = payload
    for token in path_tokens:
        if token.startswith("["):
            idx = int(token.strip("[]"))
            node = node[idx]
        else:
            key = token[1:] if token.startswith(".") else token
            node = node[key]
    return node


def delete_key_at_path(payload: Any, path_tokens: List[str]) -> Any:
    node = payload
    for token in path_tokens[:-1]:
        if token.startswith("["):
            idx = int(token.strip("[]"))
            node = node[idx]
        else:
            key = token[1:] if token.startswith(".") else token
            node = node[key]
    last = path_tokens[-1]
    if last.startswith("["):
        idx = int(last.strip("[]"))
        del node[idx]
    else:
        key = last[1:] if last.startswith(".") else last
        if isinstance(node, dict) and key in node:
            del node[key]
    return payload