jsontree.py 3.38 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
"""Helper functions to work with nested JSON structures."""
4

5
6
from collections.abc import Iterable
from functools import reduce
7
from typing import Callable, TypeVar, Union, cast, overload
8
9
10
11

_T = TypeVar("_T")
_U = TypeVar("_U")

12
13
14
15
16
17
JSONTree = Union[
    dict[str, "JSONTree[_T]"],
    list["JSONTree[_T]"],
    tuple["JSONTree[_T]", ...],
    _T,
]
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
"""A nested JSON structure where the leaves need not be JSON-serializable."""


def json_iter_leaves(value: JSONTree[_T]) -> Iterable[_T]:
    """Iterate through each leaf in a nested JSON structure."""
    if isinstance(value, dict):
        for v in value.values():
            yield from json_iter_leaves(v)
    elif isinstance(value, (list, tuple)):
        for v in value:
            yield from json_iter_leaves(v)
    else:
        yield value


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
@overload
def json_map_leaves(
    func: Callable[[_T], _U],
    value: Union[_T, dict[str, _T]],
) -> Union[_U, dict[str, _U]]:
    ...


@overload
def json_map_leaves(
    func: Callable[[_T], _U],
    value: Union[_T, list[_T]],
) -> Union[_U, list[_U]]:
    ...


@overload
def json_map_leaves(
    func: Callable[[_T], _U],
    value: Union[_T, tuple[_T, ...]],
) -> Union[_U, tuple[_U, ...]]:
    ...


@overload
58
59
60
61
def json_map_leaves(
    func: Callable[[_T], _U],
    value: JSONTree[_T],
) -> JSONTree[_U]:
62
63
64
65
66
67
68
    ...


def json_map_leaves(
    func: Callable[[_T], _U],
    value: Union[dict[str, _T], list[_T], tuple[_T, ...], JSONTree[_T]],
) -> Union[dict[str, _U], list[_U], tuple[_U, ...], JSONTree[_U]]:
69
70
71
72
73
74
75
76
77
78
79
    """Apply a function to each leaf in a nested JSON structure."""
    if isinstance(value, dict):
        return {k: json_map_leaves(func, v) for k, v in value.items()}
    elif isinstance(value, list):
        return [json_map_leaves(func, v) for v in value]
    elif isinstance(value, tuple):
        return tuple(json_map_leaves(func, v) for v in value)
    else:
        return func(value)


80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
@overload
def json_reduce_leaves(
    func: Callable[[_T, _T], _T],
    value: Union[_T, dict[str, _T]],
    /,
) -> _T:
    ...


@overload
def json_reduce_leaves(
    func: Callable[[_T, _T], _T],
    value: Union[_T, list[_T]],
    /,
) -> _T:
    ...


@overload
def json_reduce_leaves(
    func: Callable[[_T, _T], _T],
    value: Union[_T, tuple[_T, ...]],
    /,
) -> _T:
    ...


107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
@overload
def json_reduce_leaves(
    func: Callable[[_T, _T], _T],
    value: JSONTree[_T],
    /,
) -> _T:
    ...


@overload
def json_reduce_leaves(
    func: Callable[[_U, _T], _U],
    value: JSONTree[_T],
    initial: _U,
    /,
) -> _U:
    ...


def json_reduce_leaves(
127
128
129
130
        func: Callable[..., Union[_T, _U]],
        value: Union[dict[str, _T], list[_T], tuple[_T, ...], JSONTree[_T]],
        initial: _U = cast(_U, ...),  # noqa: B008
        /,
131
132
133
134
135
136
137
138
139
140
141
142
143
144
) -> Union[_T, _U]:
    """
    Apply a function of two arguments cumulatively to each leaf in a
    nested JSON structure, from left to right, so as to reduce the
    sequence to a single value.
    """
    if initial is ...:
        return reduce(func, json_iter_leaves(value))  # type: ignore[arg-type]

    return reduce(
        func,  # type: ignore[arg-type]
        json_iter_leaves(value),
        initial,
    )
145
146
147
148
149


def json_count_leaves(value: JSONTree[_T]) -> int:
    """Count the number of leaves in a nested JSON structure."""
    return sum(1 for _ in json_iter_leaves(value))