jsonyx.Decoder

class jsonyx.Decoder(*, allow=NOTHING, cache_keys=False, hooks=None)

Bases: object

A configurable JSON decoder.

Changed in version 2.0: Replaced use_decimal with hooks.`

Changed in version 2.2:

  • Added cache_keys.

  • Disabled caching keys by default.

Parameters:
  • allow (Container[str], default: NOTHING) – the JSON deviations from jsonyx.allow

  • cache_keys (bool, default: False) – re-use the keys of objects

  • hooks (dict[str, _Hook] | None, default: None) – the hooks used for transforming data

load(fp, *, root='.')[source]

Deserialize an open JSON file to a Python object.

Parameters:
  • fp (_SupportsRead[bytes | str]) – an open JSON file

  • root (_StrPath, default: ".") – the path to the archive containing this JSON file

Raises:

TruncatedSyntaxError – when failing to decode the file

Returns:

Any – a Python object

Example:
>>> import jsonyx as json
>>> from io import StringIO
>>> decoder = json.Decoder()
>>> io = StringIO('["streaming API"]')
>>> decoder.load(io)
['streaming API']

Tip

Specify root to display the zip filename in error messages.

loads(s, *, filename='<string>')[source]

Deserialize a JSON string to a Python object.

Parameters:
  • s (bytearray | bytes | str) – a JSON string

  • filename (_StrPath, default: "<string>") – the path to the JSON file

Raises:

TruncatedSyntaxError – when failing to decode the string

Returns:

Any – a Python object

Example:
>>> import jsonyx as json
>>> decoder = json.Decoder()
>>> decoder.loads('{"foo": ["bar", null, 1.0, 2]}')
{'foo': ['bar', None, 1.0, 2]}
>>> decoder.loads(r'"\"foo\bar"')
'"foo\x08ar'

Tip

Specify filename to display the filename in error messages.

read(filename)[source]

Deserialize a JSON file to a Python object.

Parameters:

filename (_StrPath) – the path to the JSON file

Raises:
Returns:

Any – a Python object

Example:
>>> import jsonyx as json
>>> from pathlib import Path
>>> from tempfile import TemporaryDirectory
>>> decoder = json.Decoder()
>>> with TemporaryDirectory() as tmpdir:
...     filename = Path(tmpdir) / "file.json"
...     _ = filename.write_text('["filesystem API"]', "utf-8")
...     decoder.read(filename)
...
['filesystem API']