hat.json
JSON Data library
1"""JSON Data library""" 2 3from hat.json.data import (Array, 4 Object, 5 Data, 6 equals, 7 clone, 8 flatten) 9from hat.json.path import (Path, 10 get, 11 set_, 12 remove, 13 Storage) 14from hat.json.encoder import (Format, 15 encode, 16 decode, 17 get_file_format, 18 encode_file, 19 decode_file, 20 encode_stream, 21 decode_stream, 22 read_conf) 23from hat.json.patch import (diff, 24 patch) 25from hat.json.schema import (SchemaId, 26 Schema, 27 SchemaRepository, 28 create_schema_repository, 29 merge_schema_repositories, 30 SchemaValidator, 31 PySchemaValidator, 32 RsSchemaValidator, 33 DefaultSchemaValidator, 34 json_schema_repo) 35from hat.json import vt 36 37 38__all__ = ['Array', 39 'Object', 40 'Data', 41 'equals', 42 'clone', 43 'flatten', 44 'Path', 45 'get', 46 'set_', 47 'remove', 48 'Storage', 49 'Format', 50 'encode', 51 'decode', 52 'get_file_format', 53 'encode_file', 54 'decode_file', 55 'encode_stream', 56 'decode_stream', 57 'read_conf', 58 'diff', 59 'patch', 60 'SchemaId', 61 'Schema', 62 'SchemaRepository', 63 'create_schema_repository', 64 'merge_schema_repositories', 65 'SchemaValidator', 66 'PySchemaValidator', 67 'RsSchemaValidator', 68 'DefaultSchemaValidator', 69 'json_schema_repo', 70 'vt']
18def equals(a: Data, 19 b: Data 20 ) -> bool: 21 """Equality comparison of json serializable data. 22 23 Tests for equality of data according to JSON format. Notably, ``bool`` 24 values are not considered equal to numeric values in any case. This is 25 different from default equality comparison, which considers `False` 26 equal to `0` and `0.0`; and `True` equal to `1` and `1.0`. 27 28 Example:: 29 30 assert equals(0, 0.0) is True 31 assert equals({'a': 1, 'b': 2}, {'b': 2, 'a': 1}) is True 32 assert equals(1, True) is False 33 34 """ 35 if a is None: 36 return b is None 37 38 if isinstance(a, bool): 39 return isinstance(b, bool) and a == b 40 41 if isinstance(a, (int, float)): 42 return (isinstance(b, (int, float)) and 43 not isinstance(b, bool) and 44 a == b) 45 46 if isinstance(a, str): 47 return isinstance(b, str) and a == b 48 49 if isinstance(a, list): 50 return (isinstance(b, list) and 51 len(a) == len(b) and 52 all(equals(i, j) for i, j in zip(a, b))) 53 54 if isinstance(a, dict): 55 return (isinstance(b, dict) and 56 len(a) == len(b) and 57 all(key in b and equals(a[key], b[key]) for key in a.keys())) 58 59 raise TypeError('invalid json type')
Equality comparison of json serializable data.
Tests for equality of data according to JSON format. Notably, bool
values are not considered equal to numeric values in any case. This is
different from default equality comparison, which considers False
equal to 0 and 0.0; and True equal to 1 and 1.0.
Example::
assert equals(0, 0.0) is True
assert equals({'a': 1, 'b': 2}, {'b': 2, 'a': 1}) is True
assert equals(1, True) is False
62def clone(data: Data) -> Data: 63 """Deep clone data 64 65 This function recursively creates new instances of array and object data 66 based on input data. Resulting json data is equal to provided data. 67 68 Example:: 69 70 x = {'a': [1, 2, 3]} 71 y = clone(x) 72 assert x is not y 73 assert x['a'] is not y['a'] 74 assert equals(x, y) 75 76 """ 77 if isinstance(data, list): 78 return [clone(i) for i in data] 79 80 if isinstance(data, dict): 81 return {k: clone(v) for k, v in data.items()} 82 83 return data
Deep clone data
This function recursively creates new instances of array and object data based on input data. Resulting json data is equal to provided data.
Example::
x = {'a': [1, 2, 3]}
y = clone(x)
assert x is not y
assert x['a'] is not y['a']
assert equals(x, y)
86def flatten(data: Data) -> Iterable[Data]: 87 """Flatten JSON data 88 89 If `data` is array, this generator recursively yields result of `flatten` 90 call with each element of input list. For other `Data` types, input data is 91 yielded. 92 93 Example:: 94 95 data = [1, [], [2], {'a': [3]}] 96 result = [1, 2, {'a': [3]}] 97 assert list(flatten(data)) == result 98 99 """ 100 if isinstance(data, list): 101 for i in data: 102 yield from flatten(i) 103 104 else: 105 yield data
16def get(data: Data, 17 path: Path, 18 default: Data | None = None 19 ) -> Data: 20 """Get data element referenced by path 21 22 Example:: 23 24 data = {'a': [1, 2, [3, 4]]} 25 path = ['a', 2, 0] 26 assert get(data, path) == 3 27 28 data = [1, 2, 3] 29 assert get(data, 0) == 1 30 assert get(data, 5) is None 31 assert get(data, 5, default=123) == 123 32 33 """ 34 for i in flatten(path): 35 if not _contains(data, i): 36 return default 37 38 data = data[i] 39 40 return data
Get data element referenced by path
Example::
data = {'a': [1, 2, [3, 4]]}
path = ['a', 2, 0]
assert get(data, path) == 3
data = [1, 2, 3]
assert get(data, 0) == 1
assert get(data, 5) is None
assert get(data, 5, default=123) == 123
43def set_(data: Data, 44 path: Path, 45 value: Data 46 ) -> Data: 47 """Create new data by setting data path element value 48 49 Example:: 50 51 data = [1, {'a': 2, 'b': 3}, 4] 52 path = [1, 'b'] 53 result = set_(data, path, 5) 54 assert result == [1, {'a': 2, 'b': 5}, 4] 55 assert result is not data 56 57 data = [1, 2, 3] 58 result = set_(data, 4, 4) 59 assert result == [1, 2, 3, None, 4] 60 61 """ 62 parents = [] 63 64 for i in flatten(path): 65 parents.append((data, i)) 66 data = data[i] if _contains(data, i) else None 67 68 for parent, i in reversed(parents): 69 value = _set(parent, i, value) 70 71 return value
Create new data by setting data path element value
Example::
data = [1, {'a': 2, 'b': 3}, 4]
path = [1, 'b']
result = set_(data, path, 5)
assert result == [1, {'a': 2, 'b': 5}, 4]
assert result is not data
data = [1, 2, 3]
result = set_(data, 4, 4)
assert result == [1, 2, 3, None, 4]
74def remove(data: Data, 75 path: Path 76 ) -> Data: 77 """Create new data by removing part of data referenced by path 78 79 Example:: 80 81 data = [1, {'a': 2, 'b': 3}, 4] 82 path = [1, 'b'] 83 result = remove(data, path) 84 assert result == [1, {'a': 2}, 4] 85 assert result is not data 86 87 data = [1, 2, 3] 88 result = remove(data, 4) 89 assert result == [1, 2, 3] 90 91 """ 92 parents = [] 93 child = data 94 95 for i in flatten(path): 96 if not _contains(child, i): 97 return data 98 99 parents.append((child, i)) 100 child = child[i] 101 102 if not parents: 103 return 104 105 parent, i = parents.pop() 106 result = dict(parent) if isinstance(parent, dict) else list(parent) 107 del result[i] 108 109 for parent, i in reversed(parents): 110 result = _set(parent, i, result) 111 112 return result
Create new data by removing part of data referenced by path
Example::
data = [1, {'a': 2, 'b': 3}, 4]
path = [1, 'b']
result = remove(data, path)
assert result == [1, {'a': 2}, 4]
assert result is not data
data = [1, 2, 3]
result = remove(data, 4)
assert result == [1, 2, 3]
115class Storage: 116 """JSON data storage 117 118 Helper class representing observable JSON data state manipulated with 119 path based get/set/remove functions. 120 121 """ 122 123 def __init__(self, data: Data = None): 124 self._data = data 125 self._change_cbs = util.CallbackRegistry() 126 127 @property 128 def data(self) -> Data: 129 """Data""" 130 return self._data 131 132 def register_change_cb(self, 133 cb: Callable[[Data], None] 134 ) -> util.RegisterCallbackHandle: 135 """Register data change callback""" 136 return self._change_cbs.register(cb) 137 138 def get(self, path: Path, default: Data | None = None) -> Data: 139 """Get data""" 140 return get(self._data, path, default) 141 142 def set(self, path: Path, value: Data): 143 """Set data""" 144 self._data = set_(self._data, path, value) 145 self._change_cbs.notify(self._data) 146 147 def remove(self, path: Path): 148 """Remove data""" 149 self._data = remove(self._data, path) 150 self._change_cbs.notify(self._data)
JSON data storage
Helper class representing observable JSON data state manipulated with path based get/set/remove functions.
Data
132 def register_change_cb(self, 133 cb: Callable[[Data], None] 134 ) -> util.RegisterCallbackHandle: 135 """Register data change callback""" 136 return self._change_cbs.register(cb)
Register data change callback
138 def get(self, path: Path, default: Data | None = None) -> Data: 139 """Get data""" 140 return get(self._data, path, default)
Get data
142 def set(self, path: Path, value: Data): 143 """Set data""" 144 self._data = set_(self._data, path, value) 145 self._change_cbs.notify(self._data)
Set data
30class Format(enum.Enum): 31 """Encoding format""" 32 JSON = 'json' 33 YAML = 'yaml' 34 TOML = 'toml'
Encoding format
37def encode(data: Data, 38 format: Format = Format.JSON, 39 indent: int | None = None, 40 sort_keys: bool = False 41 ) -> str: 42 """Encode JSON data. 43 44 In case of TOML format, data must be JSON Object. 45 46 In case of TOML format, `indent` is ignored. 47 48 In case of TOML format, `sort_keys` is ignored. 49 50 Args: 51 data: JSON data 52 format: encoding format 53 indent: indentation size 54 sort_keys: sort object keys 55 56 """ 57 if format == Format.JSON: 58 return json.dumps(data, 59 indent=indent, 60 sort_keys=sort_keys, 61 allow_nan=False) 62 63 if format == Format.YAML: 64 return str(yaml.dump(data, 65 Dumper=_yaml_dumper, 66 indent=indent, 67 sort_keys=sort_keys)) 68 69 if format == Format.TOML: 70 return tomli_w.dumps(data) 71 72 raise ValueError('unsupported format')
Encode JSON data.
In case of TOML format, data must be JSON Object.
In case of TOML format, indent is ignored.
In case of TOML format, sort_keys is ignored.
Arguments:
- data: JSON data
- format: encoding format
- indent: indentation size
- sort_keys: sort object keys
75def decode(data_str: str, 76 format: Format = Format.JSON 77 ) -> Data: 78 """Decode JSON data. 79 80 Args: 81 data_str: encoded JSON data 82 format: encoding format 83 84 """ 85 if format == Format.JSON: 86 return json.loads(data_str) 87 88 if format == Format.YAML: 89 return yaml.load(io.StringIO(data_str), Loader=_yaml_loader) 90 91 if format == Format.TOML: 92 return toml.loads(data_str) 93 94 raise ValueError('unsupported format')
Decode JSON data.
Arguments:
- data_str: encoded JSON data
- format: encoding format
97def get_file_format(path: pathlib.PurePath) -> Format: 98 """Detect file format based on path suffix""" 99 if path.suffix == '.json': 100 return Format.JSON 101 102 if path.suffix in ('.yaml', '.yml'): 103 return Format.YAML 104 105 if path.suffix == '.toml': 106 return Format.TOML 107 108 raise ValueError('can not determine format from path suffix')
Detect file format based on path suffix
111def encode_file(data: Data, 112 path: pathlib.PurePath, 113 format: Format | None = None, 114 indent: int | None = 4, 115 sort_keys: bool = False): 116 """Encode JSON data to file. 117 118 If `format` is ``None``, encoding format is derived from path suffix. 119 120 In case of TOML format, data must be JSON Object. 121 122 In case of TOML format, `indent` is ignored. 123 124 In case of TOML format, `sort_keys` is ignored. 125 126 Args: 127 data: JSON data 128 path: file path 129 format: encoding format 130 indent: indentation size 131 sort_keys: sort object keys 132 133 """ 134 if format is None: 135 format = get_file_format(path) 136 137 mode = 'w' if format != Format.TOML else 'wb' 138 encoding = 'utf-8' if format != Format.TOML else None 139 140 with open(path, mode, encoding=encoding) as f: 141 encode_stream(data=data, 142 stream=f, 143 format=format, 144 indent=indent, 145 sort_keys=sort_keys)
Encode JSON data to file.
If format is None, encoding format is derived from path suffix.
In case of TOML format, data must be JSON Object.
In case of TOML format, indent is ignored.
In case of TOML format, sort_keys is ignored.
Arguments:
- data: JSON data
- path: file path
- format: encoding format
- indent: indentation size
- sort_keys: sort object keys
148def decode_file(path: pathlib.PurePath, 149 format: Format | None = None 150 ) -> Data: 151 """Decode JSON data from file. 152 153 If `format` is ``None``, encoding format is derived from path suffix. 154 155 Args: 156 path: file path 157 format: encoding format 158 159 """ 160 if format is None: 161 format = get_file_format(path) 162 163 mode = 'r' if format != Format.TOML else 'rb' 164 encoding = 'utf-8' if format != Format.TOML else None 165 166 with open(path, mode, encoding=encoding) as f: 167 return decode_stream(f, format)
Decode JSON data from file.
If format is None, encoding format is derived from path suffix.
Arguments:
- path: file path
- format: encoding format
170def encode_stream(data: Data, 171 stream: typing.TextIO | typing.BinaryIO, 172 format: Format = Format.JSON, 173 indent: int | None = 4, 174 sort_keys: bool = False): 175 """Encode JSON data to stream. 176 177 In case of TOML format, data must be JSON Object. 178 179 In case of TOML format, `stream` should be `BinaryIO`. For 180 other formats, `TextIO` is expected. 181 182 In case of TOML format, `indent` is ignored. 183 184 In case of TOML format, `sort_keys` is ignored. 185 186 Args: 187 data: JSON data 188 stream: output stream 189 format: encoding format 190 indent: indentation size 191 sort_keys: sort object keys 192 193 """ 194 if format == Format.JSON: 195 json.dump(data, stream, 196 indent=indent, 197 sort_keys=sort_keys, 198 allow_nan=False) 199 200 elif format == Format.YAML: 201 yaml.dump(data, stream, 202 Dumper=_yaml_dumper, 203 indent=indent, 204 sort_keys=sort_keys, 205 explicit_start=True, 206 explicit_end=True) 207 208 elif format == Format.TOML: 209 tomli_w.dump(data, stream) 210 211 else: 212 raise ValueError('unsupported format')
Encode JSON data to stream.
In case of TOML format, data must be JSON Object.
In case of TOML format, stream should be BinaryIO. For
other formats, TextIO is expected.
In case of TOML format, indent is ignored.
In case of TOML format, sort_keys is ignored.
Arguments:
- data: JSON data
- stream: output stream
- format: encoding format
- indent: indentation size
- sort_keys: sort object keys
215def decode_stream(stream: typing.TextIO | typing.BinaryIO, 216 format: Format = Format.JSON 217 ) -> Data: 218 """Decode JSON data from stream. 219 220 In case of TOML format, `stream` should be `BinaryIO`. For 221 other formats, `TextIO` is expected. 222 223 Args: 224 stream: input stream 225 format: encoding format 226 227 """ 228 if format == Format.JSON: 229 return json.load(stream) 230 231 if format == Format.YAML: 232 return yaml.load(stream, Loader=_yaml_loader) 233 234 if format == Format.TOML: 235 return toml.load(stream) 236 237 raise ValueError('unsupported format')
Decode JSON data from stream.
In case of TOML format, stream should be BinaryIO. For
other formats, TextIO is expected.
Arguments:
- stream: input stream
- format: encoding format
240def read_conf(path: pathlib.Path | None, 241 default_path: pathlib.Path | None = None, 242 default_suffixes: Iterable[str] = ('.yaml', '.yml', '.toml', 243 '.json'), 244 stdio_path: pathlib.Path | None = pathlib.Path('-') 245 ) -> Data: 246 """Read configuration formatted as JSON data""" 247 if stdio_path and path == stdio_path: 248 return decode_stream(sys.stdin) 249 250 if path: 251 return decode_file(path) 252 253 if not default_path: 254 raise Exception('invalid configuration path') 255 256 for suffix in default_suffixes: 257 path = default_path.with_suffix(suffix) 258 if path.exists(): 259 return decode_file(path) 260 261 raise Exception('configuration not found')
Read configuration formatted as JSON data
13def diff(src: Data, 14 dst: Data 15 ) -> Data: 16 """Generate JSON Patch diff. 17 18 Example:: 19 20 src = [1, {'a': 2}, 3] 21 dst = [1, {'a': 4}, 3] 22 result = diff(src, dst) 23 assert result == [{'op': 'replace', 'path': '/1/a', 'value': 4}] 24 25 """ 26 return list(_diff(src, dst))
Generate JSON Patch diff.
Example::
src = [1, {'a': 2}, 3]
dst = [1, {'a': 4}, 3]
result = diff(src, dst)
assert result == [{'op': 'replace', 'path': '/1/a', 'value': 4}]
124def patch(data: Data, 125 diff: Data 126 ) -> Data: 127 """Apply JSON Patch diff. 128 129 Example:: 130 131 data = [1, {'a': 2}, 3] 132 d = [{'op': 'replace', 'path': '/1/a', 'value': 4}] 133 result = patch(data, d) 134 assert result == [1, {'a': 4}, 3] 135 136 """ 137 for op in diff: 138 data = _apply_op(data, op) 139 140 return data
Apply JSON Patch diff.
Example::
data = [1, {'a': 2}, 3]
d = [{'op': 'replace', 'path': '/1/a', 'value': 4}]
result = patch(data, d)
assert result == [1, {'a': 4}, 3]
34def create_schema_repository(*args: pathlib.Path | Schema 35 ) -> SchemaRepository: 36 """Create JSON Schema repository. 37 38 Repository can be initialized with multiple arguments, which can be 39 instances of ``pathlib.Path`` or ``Schema``. 40 41 If an argument is of type ``pathlib.Path``, and path points to file 42 with a suffix '.json', '.yml' or '.yaml', json serializable data is decoded 43 from the file. Otherwise, it is assumed that path points to a directory, 44 which is recursively searched for json and yaml files. All decoded schemas 45 are added to the repository. If a schema with the same `id` was previously 46 added, an exception is raised. 47 48 If an argument is of type ``Schema``, it should be a json serializable data 49 representation of a JSON schema. If a schema with the same `id` was 50 previously added, an exception is raised. 51 52 """ 53 repo = {} 54 55 for arg in args: 56 if isinstance(arg, pathlib.Path): 57 if arg.suffix in _schema_path_suffixes: 58 paths = [arg] 59 60 else: 61 paths = itertools.chain.from_iterable( 62 arg.rglob(f'*{i}') for i in _schema_path_suffixes) 63 64 schemas = (decode_file(path) for path in paths) 65 66 elif isinstance(arg, dict): 67 schemas = [arg] 68 69 else: 70 raise TypeError('invalid argument type') 71 72 for schema in schemas: 73 if '$schema' in schema: 74 meta_schema_id = urllib.parse.urldefrag(schema['$schema']).url 75 if meta_schema_id not in _meta_schema_ids: 76 raise Exception( 77 f"unsupported meta schema id {meta_schema_id}") 78 79 else: 80 schema = {'$schema': _default_meta_schema_id, 81 **schema} 82 83 schema_id = schema.get('$id') or schema.get('id') 84 if not schema_id: 85 raise Exception('invalid schema id') 86 87 sanitized_schema_id = urllib.parse.urldefrag(schema_id).url 88 if sanitized_schema_id in repo: 89 raise Exception(f"duplicate schema id {sanitized_schema_id}") 90 91 repo[sanitized_schema_id] = schema 92 93 return repo
Create JSON Schema repository.
Repository can be initialized with multiple arguments, which can be
instances of pathlib.Path or Schema.
If an argument is of type pathlib.Path, and path points to file
with a suffix '.json', '.yml' or '.yaml', json serializable data is decoded
from the file. Otherwise, it is assumed that path points to a directory,
which is recursively searched for json and yaml files. All decoded schemas
are added to the repository. If a schema with the same id was previously
added, an exception is raised.
If an argument is of type Schema, it should be a json serializable data
representation of a JSON schema. If a schema with the same id was
previously added, an exception is raised.
96def merge_schema_repositories(*repos: SchemaRepository 97 ) -> SchemaRepository: 98 """Merge JSON Schema repositories. 99 100 Exception is raised if multiple repositories contain same schema id with 101 different schemas. 102 103 """ 104 result = {} 105 106 for repo in repos: 107 for schema_id, schema in repo.items(): 108 other_schema = result.get(schema_id) 109 if other_schema is not None and other_schema != schema: 110 raise Exception(f"conflict for schema id {schema_id}") 111 112 result[schema_id] = schema 113 114 return result
Merge JSON Schema repositories.
Exception is raised if multiple repositories contain same schema id with different schemas.
117class SchemaValidator(abc.ABC): 118 """JSON Schema validator interface 119 120 Args: 121 repo: repository containing JSON Schemas 122 123 """ 124 125 @abc.abstractmethod 126 def __init__(self, repo: SchemaRepository): 127 pass 128 129 @abc.abstractmethod 130 def validate(self, schema_id: SchemaId, data: Data): 131 """Validate data against JSON Schema. 132 133 Args: 134 schema_id: JSON schema identifier 135 data: data to be validated 136 137 Raises: 138 Exception 139 140 """
JSON Schema validator interface
Arguments:
- repo: repository containing JSON Schemas
129 @abc.abstractmethod 130 def validate(self, schema_id: SchemaId, data: Data): 131 """Validate data against JSON Schema. 132 133 Args: 134 schema_id: JSON schema identifier 135 data: data to be validated 136 137 Raises: 138 Exception 139 140 """
Validate data against JSON Schema.
Arguments:
- schema_id: JSON schema identifier
- data: data to be validated
Raises:
- Exception
143class PySchemaValidator(SchemaValidator): 144 """Python implementation of SchemaValidator""" 145 146 def __init__(self, repo: SchemaRepository): 147 self._repo = repo 148 self._registry = referencing.Registry(retrieve=self._retrieve) 149 150 def validate(self, schema_id: SchemaId, data: Data): 151 jsonschema.validate(instance=data, 152 schema={'$ref': schema_id}, 153 registry=self._registry) 154 155 def _retrieve(self, uri): 156 try: 157 schema = self._repo[uri] 158 159 except KeyError: 160 raise referencing.exceptions.NoSuchResource(uri) 161 162 return referencing.Resource.from_contents(schema)
Python implementation of SchemaValidator
150 def validate(self, schema_id: SchemaId, data: Data): 151 jsonschema.validate(instance=data, 152 schema={'$ref': schema_id}, 153 registry=self._registry)
Validate data against JSON Schema.
Arguments:
- schema_id: JSON schema identifier
- data: data to be validated
Raises:
- Exception
165class RsSchemaValidator(SchemaValidator): 166 """Rust implementation of SchemaValidator""" 167 168 def __init__(self, repo: SchemaRepository): 169 if not jsonschema_rs: 170 raise Exception('implementation not available') 171 172 self._repo = repo 173 self._defs = {i: {'$ref': i} for i in self._repo.keys()} 174 175 def validate(self, schema_id: SchemaId, data: Data): 176 jsonschema_rs.validate(schema={'$ref': schema_id, 177 '$defs': self._defs}, 178 instance=data, 179 retriever=self._retriever) 180 181 def _retriever(self, uri): 182 return self._repo[uri]
Rust implementation of SchemaValidator
175 def validate(self, schema_id: SchemaId, data: Data): 176 jsonschema_rs.validate(schema={'$ref': schema_id, 177 '$defs': self._defs}, 178 instance=data, 179 retriever=self._retriever)
Validate data against JSON Schema.
Arguments:
- schema_id: JSON schema identifier
- data: data to be validated
Raises:
- Exception