JSON¶
In order to better support JSON, you should declare each of your class that supports being converted to JSON with
- class satella.json.JSONAble¶
- abstract to_json()¶
Return a JSON-able representation of this object
- Return type:
Jsonable
- class satella.json.JSONAbleDataObject(**kwargs)¶
A data-class that supports conversion of its classes to JSON
Define like this:
>>> class CultureContext(JSONAbleDataObject): >>> language: str >>> timezone: str >>> units: str = 'metric'
Note that type annotation is mandatory and default values are supported. Being data value objects, these are eq-able and hashable.
And use like this:
>>> a = CultureContext(language='pl', timezone='Europe/Warsaw') >>> assert a.to_json() == {'language': 'pl', 'timezone': 'Europe/Warsaw', 'units': 'metric'} >>> assert CultureContext.from_json(a.to_json) == a
- Raises:
ValueError – a non-default value was not provided
- to_json()¶
Convert self to JSONable value
- Return type:
Dict
Then you can convert structures made out of standard serializable Python JSON objects, such as dicts and lists, and also JSONAble objects, by this all
- satella.json.json_encode(x)¶
Convert an object to JSON. Will properly handle subclasses of JSONAble
- Parameters:
x (Any) – object to convert
- Return type:
str
You might also want to check out the JSONEncoder satella uses to do it.
- class satella.json.JSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)¶
This encoder will encode everything!
enums will be dumped to their value.
Constructor for JSONEncoder, with sensible defaults.
If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float or None. If skipkeys is True, such items are simply skipped.
If ensure_ascii is true, the output is guaranteed to be str objects with all incoming non-ASCII characters escaped. If ensure_ascii is false, the output can contain non-ASCII characters.
If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an RecursionError). Otherwise, no such check takes place.
If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.
If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.
If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.
If specified, separators should be an (item_separator, key_separator) tuple. The default is (’, ‘, ‘: ‘) if indent is
None
and (‘,’, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (‘,’, ‘:’) to eliminate whitespace.If specified, default is a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a
TypeError
.- default(o)¶
Implement this method in a subclass such that it returns a serializable object for
o
, or calls the base implementation (to raise aTypeError
).For example, to support arbitrary iterators, you could implement default like this:
def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) # Let the base class default method raise the TypeError return JSONEncoder.default(self, o)
- Parameters:
o (Any) –
- Return type:
Jsonable
This will serialize unknown objects in the following way. First, __dict__ will be extracted out of this object. The dictionary will be constructed in such a way, that for each key in this __dict__, it’s value’s repr will be assigned.
- satella.json.read_json_from_file(path)¶
Load a JSON from a provided file, as UTF-8 encoded plain text.
- Parameters:
path (str) – path to the file
- Returns:
JSON content
- Raises:
ValueError – the file contained an invalid JSON
OSError – the file was not readable or did not exist
- Return type:
- satella.json.write_json_to_file(path, value, **kwargs)¶
Write out a JSON to a file as UTF-8 encoded plain text.
This will use Satella’s
JSONEncoder
internally.- Parameters:
path (str) – path to the file
value (JSONAble) – JSON-able content
kwargs – Legacy argument do not use it, will raise a warning upon non-empty. This never did anything.
- Return type:
None
- satella.json.write_json_to_file_if_different(path, value, encoding='utf-8', **kwargs)¶
Read JSON from a file. Write out a JSON to a file if it’s value is different, as UTF-8 encoded plain text.
This will use Satella’s
JSONEncoder
internally.- Parameters:
path (str) – path to the file
value (JSONAble) – JSON-able content
encoding (str) – encoding to use while parsing the contents of the file
kwargs – will be passed to ujson/json dumps
- Returns:
whether the write actually happened
- Return type:
bool