Encoder¶
Note
Checkout the getting started guide for more details on encoding.
Implements the JSON5Encoder class and the dumps and dump functions.
JSON5Encoder ¶
JSON5Encoder(
*,
default: DefaultInterface | None = None,
skip_keys: bool = False,
ensure_ascii: bool = True,
check_circular: bool = True,
allow_nan: bool = True,
indent: int | None = None,
separators: tuple[str, str] | None = None,
sort_keys: bool = False,
key_quotation: KeyQuotation = "double",
trailing_comma: bool | None = None,
)
JSON5 encoder class. This encoder is used to serialize Python objects to JSON5 strings. This class mirrors the standard library's JSONEncoder class, with the addition of a few extra options and features. This class will transform common data structures according to this table:
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float | number |
True | true |
False | false |
None | null |
To extend the encoder, subclass this class and override the
.default()
method, which will try to encode the
data structures that are not supported by default. The
.default()
method should return a serializable object.
If the .default()
method is not overridden, the encoder
will raise a JSON5EncodeError when trying to encode an unsupported object. The overridden
.default()
method should also call the parent class's
.default()
method to handle the default encoding.
The constructor also takes in a default
argument, which can be used to set a default
function that will be called when trying to encode an unsupported object. This argument
will take precedence over the overridden
.default()
method.
Warning
Comment extraction is currently only fully supported on Python 3.12+. On older versions, the function will still work but will not extract all comments from the parent TypedDicts.
Example:
import ujson5
class MyEncoder(ujson5.JSON5Encoder):
def default(self, obj):
if isinstance(obj, set): # (1)!
return list(obj)
return super().default(obj) # (2)!
user = {"name": "John", "age": "123", "hobbies": {"tennis", "reading"}}
print(ujson5.dumps(user, cls=MyEncoder))
# {"name": "John", "age": "123", "hobbies": ["reading", "tennis"]}
- In this example, the encoder subclass
MyEncoder
overrides the.default()
method to handle the serialization of sets. The method returns a list of the set elements. - It is recommended to call the parent class's
.default()
method to handle the default encoding.
All arguments are keyword-only arguments.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
default
|
DefaultInterface | None
|
A function that returns a serializable object when trying to encode an
unsupported object. If None, the default |
None
|
skip_keys
|
bool
|
If True, keys with unsupported types (anything other than str, int, float, bool, or None) will be skipped. Otherwise, an exception will be raised. Defaults to False. |
False
|
ensure_ascii
|
bool
|
If True, all non-ASCII characters will be escaped. Defaults to True. |
True
|
check_circular
|
bool
|
If True, circular references will be checked. This will introduce a small performance hit. Defaults to True. |
True
|
allow_nan
|
bool
|
If True, NaN, Infinity, and -Infinity will be allowed. Otherwise, an exception will be raised when trying to encode these values. Defaults to True. |
True
|
indent
|
int | None
|
If not None, the output will be formatted with the given indent level. Otherwise, the output will be compact. Defaults to None. |
None
|
separators
|
tuple[str, str] | None
|
A tuple containing the item separator and the key-value separator. Defaults to None. If None, it will be set to (", ", ": ") if indent is None, and (",", ":") if indent is not None. |
None
|
sort_keys
|
bool
|
If True, the keys will be sorted. Defaults to False. |
False
|
key_quotation
|
KeyQuotation
|
The quotation style to be used for keys. Can be one of "single", "double", or "none". If "single" or "double", the keys will be enclosed in single or double quotes, respectively. If "none", the keys will not be enclosed in quotes. Defaults to "double". |
'double'
|
trailing_comma
|
bool | None
|
If True, a trailing comma will be added to the last item in a list or dictionary. If None, a trailing comma will be added if indent is not None. Defaults to None. |
None
|
Source code in src/ujson5/encoder.py
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
|
encode ¶
Return a JSON5 string representation of a Python object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj
|
Any
|
The Python object to be serialized |
required |
typed_dict_cls
|
Any | None
|
A TypedDict class that will be used to extract comments from the TypedDict entries. Defaults to None. |
None
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The JSON5 string representation of the Python object |
Raises:
Type | Description |
---|---|
JSON5EncodeError
|
If the TypedDict class is not a TypedDict subclass or if the object cannot be serialized |
Source code in src/ujson5/encoder.py
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 |
|
iterencode ¶
Encode the given object and yield each part of the JSON5 string representation
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj
|
Any
|
The Python object to be serialized |
required |
typed_dict_cls
|
Any | None
|
A TypedDict class that will be used to extract comments from the TypedDict entries. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
Iterable[str]
|
Iterable[str]: An iterable of strings representing the JSON5 serialization of the Python object |
Raises:
Type | Description |
---|---|
JSON5EncodeError
|
If the TypedDict class is not a TypedDict subclass or if the object cannot be serialized |
Source code in src/ujson5/encoder.py
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 |
|
default ¶
default(obj: Any) -> Serializable
Override this method in a subclass to implement custom serialization for objects that are not serializable by default. This method should return a serializable object. If this method is not overridden, the encoder will raise a JSON5EncodeError when trying to encode an unsupported object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj
|
Any
|
The object to be serialized that is not supported by default |
required |
Returns:
Name | Type | Description |
---|---|---|
Serializable |
Serializable
|
A serializable object |
Raises:
Type | Description |
---|---|
JSON5EncodeError
|
If the object cannot be serialized |
Source code in src/ujson5/encoder.py
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 |
|
dump ¶
dump(
obj: Any,
fp: TextIO,
typed_dict_cls: Any | None = None,
*,
skip_keys: bool = False,
ensure_ascii: bool = True,
check_circular: bool = True,
allow_nan: bool = True,
cls: type[JSON5Encoder] | None = None,
indent: int | None = None,
separators: tuple[str, str] | None = None,
default: DefaultInterface | None = None,
sort_keys: bool = False,
key_quotation: KeyQuotation = "double",
trailing_comma: bool | None = None,
) -> None
Serialize obj
as a JSON formatted stream to fp
(a .write()
-supporting
file-like object).
Example:
import ujson5
user = {"name": "John", "age": 123, "hobbies": ["tennis", "reading"]}
with open("user.json", "w") as f:
ujson5.dump(user, f)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cls
|
type[JSON5Encoder] | None
|
The encoder class to be used. a custom |
None
|
default
|
DefaultInterface | None
|
A function that returns a serializable object when trying to encode an
unsupported object. If None, the default
|
None
|
skip_keys
|
bool
|
If True, keys with unsupported types (anything other than str, int, float, bool, or None) will be skipped. Otherwise, an exception will be raised. Defaults to False. |
False
|
ensure_ascii
|
bool
|
If True, all non-ASCII characters will be escaped. Defaults to True. |
True
|
check_circular
|
bool
|
If True, circular references will be checked. This will introduce a small performance hit. Defaults to True. |
True
|
allow_nan
|
bool
|
If True, NaN, Infinity, and -Infinity will be allowed. Otherwise, an exception will be raised when trying to encode these values. Defaults to True. |
True
|
indent
|
int | None
|
If not None, the output will be formatted with the given indent level. Otherwise, the output will be compact. Defaults to None. |
None
|
separators
|
tuple[str, str] | None
|
A tuple containing the item separator and the key-value separator. Defaults to None. If None, it will be set to (", ", ": ") if indent is None, and (",", ":") if indent is not None. |
None
|
sort_keys
|
bool
|
If True, the keys will be sorted. Defaults to False. |
False
|
key_quotation
|
KeyQuotation
|
The quotation style to be used for keys. Can be one of "single", "double", or "none". If "single" or "double", the keys will be enclosed in single or double quotes, respectively. If "none", the keys will not be enclosed in quotes. Defaults to "double". |
'double'
|
trailing_comma
|
bool | None
|
If True, a trailing comma will be added to the last item in a list or dictionary. If None, a trailing comma will be added if indent is not None. Defaults to None. |
None
|
Returns:
Name | Type | Description |
---|---|---|
str |
None
|
The JSON5 formatted string representation of the Python object |
Raises:
Type | Description |
---|---|
JSON5EncodeError
|
If the object cannot be serialized |
Source code in src/ujson5/encoder.py
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 |
|
dumps ¶
dumps(
obj: Any,
typed_dict_cls: Any | None = None,
*,
cls: type[JSON5Encoder] | None = None,
default: DefaultInterface | None = None,
skip_keys: bool = False,
ensure_ascii: bool = True,
check_circular: bool = True,
allow_nan: bool = True,
indent: int | None = None,
separators: tuple[str, str] | None = None,
sort_keys: bool = False,
key_quotation: KeyQuotation = "double",
trailing_comma: bool | None = None,
) -> str
Serialize obj
to a JSON5 formatted str
.
Example:
import ujson5
user = {"name": "John", "age": 123, "hobbies": ["tennis", "reading"]}
print(ujson5.dumps(user))
# Output: '{"name": "John", "age": 123, "hobbies": ["tennis", "reading"]}'
All arguments except obj
and typed_dict_cls
are keyword-only arguments.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cls
|
type[JSON5Encoder] | None
|
The encoder class to be used. a custom |
None
|
default
|
DefaultInterface | None
|
A function that returns a serializable object when trying to encode an
unsupported object. If None, the default
|
None
|
skip_keys
|
bool
|
If True, keys with unsupported types (anything other than str, int, float, bool, or None) will be skipped. Otherwise, an exception will be raised. Defaults to False. |
False
|
ensure_ascii
|
bool
|
If True, all non-ASCII characters will be escaped. Defaults to True. |
True
|
check_circular
|
bool
|
If True, circular references will be checked. This will introduce a small performance hit. Defaults to True. |
True
|
allow_nan
|
bool
|
If True, NaN, Infinity, and -Infinity will be allowed. Otherwise, an exception will be raised when trying to encode these values. Defaults to True. |
True
|
indent
|
int | None
|
If not None, the output will be formatted with the given indent level. Otherwise, the output will be compact. Defaults to None. |
None
|
separators
|
tuple[str, str] | None
|
A tuple containing the item separator and the key-value separator. Defaults to None. If None, it will be set to (", ", ": ") if indent is None, and (",", ":") if indent is not None. |
None
|
sort_keys
|
bool
|
If True, the keys will be sorted. Defaults to False. |
False
|
key_quotation
|
KeyQuotation
|
The quotation style to be used for keys. Can be one of "single", "double", or "none". If "single" or "double", the keys will be enclosed in single or double quotes, respectively. If "none", the keys will not be enclosed in quotes. Defaults to "double". |
'double'
|
trailing_comma
|
bool | None
|
If True, a trailing comma will be added to the last item in a list or dictionary. If None, a trailing comma will be added if indent is not None. Defaults to None. |
None
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The JSON5 formatted string representation of the Python object |
Raises:
Type | Description |
---|---|
JSON5EncodeError
|
If the object cannot be serialized |
Source code in src/ujson5/encoder.py
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 |
|
Implements the JSON5Encoder class and the dumps and dump functions.
DefaultInterface
module-attribute
¶
DefaultInterface = (
Callable[[Any], dict]
| Callable[[Any], list]
| Callable[[Any], tuple]
| Callable[[Any], int]
| Callable[[Any], float]
| Callable[[Any], str]
| Callable[[Any], None]
| Callable[[Any], bool]
| Callable[[Any], Serializable]
)
A callable that takes in an object that is not serializable and returns a serializable object
Serializable
module-attribute
¶
Python objects that can be serialized to JSON5
relative_crossrefs: true