jsonyx.dump

jsonyx.dump(obj, fp=None, *, allow=NOTHING, check_circular=True, commas=True, end='\\n', ensure_ascii=False, hook=None, indent=None, indent_leaves=True, max_indent_level=None, quoted_keys=True, separators=(', ', ': '), skipkeys=False, sort_keys=False, trailing_comma=False, types=None)[source]

Serialize a Python object to an open JSON file.

Changed in version 2.0:

  • Added commas, indent_leaves, max_indent_level, quoted_keys and types.

  • Made tuple serializable by default instead of enum.Enum and decimal.Decimal.

  • Replaced item_separator and key_separator with separators.

Changed in version 2.1: Added check_circular, hook and skipkeys.

Parameters:
  • obj (object) – a Python object

  • fp (_SupportsWrite[str] | None, default: None) – an open JSON file

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

  • check_circular (bool, default: True) – check for circular references

  • commas (bool, default: True) – separate items by commas when indented

  • end (str, default: "\\n") – the string to append at the end

  • ensure_ascii (bool, default: False) – escape non-ASCII characters

  • hook (_Hook | None, default: None) – the hook used for transforming data

  • indent (int | str | None, default: None) – the number of spaces or string to indent with

  • indent_leaves (bool, default: True) – indent leaf objects and arrays

  • max_indent_level (int | None, default: None) – the level up to which to indent

  • quoted_keys (bool, default: True) – quote keys which are identifiers

  • separators (tuple[str, str], default: (", ", ": ")) – the item and key separator

  • skipkeys (bool, default: False) – skip non-string keys

  • sort_keys (bool, default: False) – sort the keys of objects

  • trailing_comma (bool, default: False) – add a trailing comma when indented

  • types (dict[str, type | tuple[type, ...]] | None, default: None) – a dictionary of additional types

Raises:
Example:

Writing to standard output:

>>> import jsonyx as json
>>> json.dump('"foo\bar')
"\"foo\bar"
>>> json.dump("\\")
"\\"
>>> json.dump("\u20AC")
"€"

Writing to an open file:

>>> import jsonyx as json
>>> from io import StringIO
>>> io = StringIO()
>>> json.dump(["streaming API"], io)
>>> io.getvalue()
'["streaming API"]\n'

Note

The item separator is automatically stripped when indented.

Warning

Avoid specifying ABCs for types, that is very slow.