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 67 68 69 70 71 72 73 74 75 76 77 78 79 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 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
|
# SPDX-License-Identifier: MIT
#
# Copyright (C) 2023 EfficiOS, inc.
#
# pyright: strict, reportTypeCommentUsage=false
import re
import json
import typing
from typing import (
Any,
Dict,
List,
Type,
Union,
TextIO,
Generic,
Mapping,
TypeVar,
Optional,
Sequence,
overload,
)
# Internal type aliases and variables
_RawArrayT = List["_RawValT"]
_RawObjT = Dict[str, "_RawValT"]
_RawValT = Union[None, bool, int, float, str, _RawArrayT, _RawObjT]
_RawValTV = TypeVar("_RawValTV", bound="_RawValT")
_ValTV = TypeVar("_ValTV", bound="Val")
# Type of a single JSON value path element.
PathElemT = Union[str, int]
# A JSON value path.
class Path:
def __init__(self, elems: Optional[List[PathElemT]] = None):
if elems is None:
elems = []
self._elems = elems
# Elements of this path.
@property
def elems(self):
return self._elems
# Returns a new path containing the current elements plus `elem`.
def __truediv__(self, elem: PathElemT):
return Path(self._elems + [elem])
# Returns a valid jq filter.
def __str__(self):
s = ""
for elem in self._elems:
if type(elem) is str:
if re.match(r"[a-zA-Z]\w*$", elem):
s += ".{}".format(elem)
else:
s += '."{}"'.format(elem)
else:
assert type(elem) is int
s += "[{}]".format(elem)
if not s.startswith("."):
s = "." + s
return s
# Base of any JSON value.
class Val:
_name = "a value"
def __init__(self, path: Optional[Path] = None):
if path is None:
path = Path()
self._path = path
# Path to this JSON value.
@property
def path(self):
return self._path
# JSON null value.
class NullVal(Val):
_name = "a null"
# JSON scalar value.
class _ScalarVal(Val, Generic[_RawValTV]):
def __init__(self, raw_val: _RawValTV, path: Optional[Path] = None):
super().__init__(path)
self._raw_val = raw_val
# Raw value.
@property
def val(self):
return self._raw_val
# JSON boolean value.
class BoolVal(_ScalarVal[bool]):
_name = "a boolean"
def __bool__(self):
return self.val
# JSON integer value.
class IntVal(_ScalarVal[int]):
_name = "an integer"
def __int__(self):
return self.val
# JSON floating point number value.
class FloatVal(_ScalarVal[float]):
_name = "a floating point number"
def __float__(self):
return self.val
# JSON string value.
class StrVal(_ScalarVal[str]):
_name = "a string"
def __str__(self):
return self.val
# JSON array value.
class ArrayVal(Val, Sequence[Val]):
_name = "an array"
def __init__(self, raw_val: _RawArrayT, path: Optional[Path] = None):
super().__init__(path)
self._raw_val = raw_val
# Returns the value at index `index`.
#
# Raises `TypeError` if the type of the returned value isn't
# `expected_elem_type`.
def at(self, index: int, expected_elem_type: Type[_ValTV]):
try:
elem = self._raw_val[index]
except IndexError:
raise IndexError(
"`{}`: array index {} out of range".format(self._path, index)
)
return wrap(elem, self._path / index, expected_elem_type)
# Returns an iterator yielding the values of this array value.
#
# Raises `TypeError` if the type of any yielded value isn't
# `expected_elem_type`.
def iter(self, expected_elem_type: Type[_ValTV]):
for i in range(len(self._raw_val)):
yield self.at(i, expected_elem_type)
@overload
def __getitem__(self, index: int) -> Val:
...
@overload
def __getitem__(self, index: slice) -> Sequence[Val]:
...
def __getitem__(self, index: Union[int, slice]) -> Union[Val, Sequence[Val]]:
if type(index) is slice:
raise NotImplementedError
return self.at(index, Val)
def __len__(self):
return len(self._raw_val)
# JSON object value.
class ObjVal(Val, Mapping[str, Val]):
_name = "an object"
def __init__(self, raw_val: _RawObjT, path: Optional[Path] = None):
super().__init__(path)
self._raw_val = raw_val
# Returns the value having the key `key`.
#
# Raises `TypeError` if the type of the returned value isn't
# `expected_type`.
def at(self, key: str, expected_type: Type[_ValTV]):
try:
val = self._raw_val[key]
except KeyError:
raise KeyError("`{}`: no value has the key `{}`".format(self._path, key))
return wrap(val, self._path / key, expected_type)
def __getitem__(self, key: str) -> Val:
return self.at(key, Val)
def __len__(self):
return len(self._raw_val)
def __iter__(self):
return iter(self._raw_val)
# Raises `TypeError` if the type of `val` is not `expected_type`.
def _check_type(val: Val, expected_type: Type[Val]):
if not isinstance(val, expected_type):
raise TypeError(
"`{}`: expecting {} value, got {}".format(
val.path,
expected_type._name,
type(val)._name,
)
)
# Wraps the raw value `raw_val` into an equivalent instance of some
# `Val` subclass having the path `path` and returns it.
#
# If the resulting JSON value type isn't `expected_type`, then this
# function raises `TypeError`.
def wrap(
raw_val: _RawValT, path: Optional[Path] = None, expected_type: Type[_ValTV] = Val
) -> _ValTV:
val = None
if raw_val is None:
val = NullVal(path)
elif isinstance(raw_val, bool):
val = BoolVal(raw_val, path)
elif isinstance(raw_val, int):
val = IntVal(raw_val, path)
elif isinstance(raw_val, float):
val = FloatVal(raw_val, path)
elif isinstance(raw_val, str):
val = StrVal(raw_val, path)
elif isinstance(raw_val, list):
val = ArrayVal(raw_val, path)
else:
assert isinstance(raw_val, dict)
val = ObjVal(raw_val, path)
assert val is not None
_check_type(val, expected_type)
return typing.cast(_ValTV, val)
# Like json.loads(), but returns a `Val` instance, raising `TypeError`
# if its type isn't `expected_type`.
def loads(s: str, expected_type: Type[_ValTV] = Val, **kwargs: Any) -> _ValTV:
return wrap(json.loads(s, **kwargs), Path(), expected_type)
# Like json.load(), but returns a `Val` instance, raising `TypeError` if
# its type isn't `expected_type`.
def load(fp: TextIO, expected_type: Type[_ValTV] = Val, **kwargs: Any) -> _ValTV:
return wrap(json.load(fp, **kwargs), Path(), expected_type)
|