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() Jsonable

Return a JSON-able representation of this object

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: Any) str

Convert an object to JSON. Will properly handle subclasses of JSONAble

Parameters:

x – object to convert

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.

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: str) JSONAble

Load a JSON from a provided file, as UTF-8 encoded plain text.

Parameters:

path – 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

satella.json.write_json_to_file(path: str, value: JSONAble, **kwargs) None

Write out a JSON to a file as UTF-8 encoded plain text.

This will use Satella’s JSONEncoder internally.

Parameters:
  • path – path to the file

  • value – JSON-able content

  • kwargs – Legacy argument do not use it, will raise a warning upon non-empty. This never did anything.

satella.json.write_json_to_file_if_different(path: str, value: JSONAble, encoding: str = 'utf-8', **kwargs) bool

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 – path to the file

  • value – JSON-able content

  • encoding – encoding to use while parsing the contents of the file

  • kwargs – will be passed to ujson/json dumps

Returns:

whether the write actually happened