Serializer / Encoder¶
The serializer returns ASCII data that can safely be used in an HTML template. Apostrophes, ampersands, greater-than, and less-then signs are encoded as unicode escaped sequences. E.g. this snippet is safe for any and all input:
"<a onclick='alert(" + encode(data) + ")'>show message</a>"
Unless the input contains infinite or NaN values, the result will be valid JSON data.
Quick Encoder Summary¶
|
Serializes a Python object to a JSON5 compatible unicode string. |
|
Serializes a Python object to a JSON5 compatible bytes string. |
|
Serializes a Python object into a callback function. |
|
Serializes a Python object into a file-object. |
|
Test if the input is serializable. |
|
Serializes a Python object to a JSON5 compatible unicode string. |
|
Serializes a Python object to a JSON5 compatible unicode string. |
Customizations for the |
|
Base class of any exception thrown by the serializer. |
|
|
The encoder was not able to stringify the input, or it was told not to by the supplied |
Full Encoder Description¶
- pyjson5.encode(data, *, options=None, **options_kw)¶
Serializes a Python object to a JSON5 compatible unicode string.
encode(['Hello', 'world!']) == '["Hello","world!"]'
- Parameters
- Raises
Json5EncoderException – An exception occured while encoding.
TypeError – An argument had a wrong type.
- Returns
Unless
float('inf')orfloat('nan')is encountered, the result will be valid JSON data (as of RFC8259).The result is always ASCII. All characters outside of the ASCII range are encoded.
The result safe to use in an HTML template, e.g.
<a onclick='alert({{ encode(url) }})'>show message</a>. Apostrophes"'"are encoded as"\u0027", less-than, greater-than, and ampersand likewise.- Return type
- pyjson5.encode_bytes(data, *, options=None, **options_kw)¶
Serializes a Python object to a JSON5 compatible bytes string.
encode_bytes(['Hello', 'world!']) == b'["Hello","world!"]'
- Parameters
data (object) – see `encode(...) <pyjson5.encode_>`_
options (Optional[Options]) – see `encode(...) <pyjson5.encode_>`_
options_kw – see `encode(...) <pyjson5.encode_>`_
- Raises
Json5EncoderException – An exception occured while encoding.
TypeError – An argument had a wrong type.
- Returns
- Return type
- pyjson5.encode_callback(data, cb, supply_bytes=False, *, options=None, **options_kw)¶
Serializes a Python object into a callback function.
The callback function
cbgets called with single characters and strings until the inputdatais fully serialized.encode_callback(['Hello', 'world!'], print) #prints: # [ # " # Hello # " # , # " # world! # " " ]
- Parameters
data (object) – see `encode(...) <pyjson5.encode_>`_
cb (Callable[[Union[bytes|str]], None]) – A callback function. Depending on the truthyness of
supply_byteseitherbytesorstris supplied.supply_bytes (bool) – Call
cb(...)with abytesargument if true, otherwisestr.options (Optional[Options]) – see `encode(...) <pyjson5.encode_>`_
options_kw – see `encode(...) <pyjson5.encode_>`_
- Raises
Json5EncoderException – An exception occured while encoding.
TypeError – An argument had a wrong type.
- Returns
The supplied argument
cb.- Return type
- pyjson5.encode_io(data, fp, supply_bytes=True, *, options=None, **options_kw)¶
Serializes a Python object into a file-object.
The return value of
fp.write(...)is not checked. Iffpis unbuffered, then the result will be garbage!- Parameters
data (object) – see `encode(...) <pyjson5.encode_>`_
fp (IOBase) – A file-like object to serialize into.
supply_bytes (bool) – Call
fp.write(...)with abytesargument if true, otherwisestr.options (Optional[Options]) – see `encode(...) <pyjson5.encode_>`_
options_kw – see `encode(...) <pyjson5.encode_>`_
- Raises
Json5EncoderException – An exception occured while encoding.
TypeError – An argument had a wrong type.
- Returns
The supplied argument
fp.- Return type
IOBase
- pyjson5.encode_noop(data, *, options=None, **options_kw)¶
Test if the input is serializable.
Most likely you want to serialize
datadirectly, and catch exceptions instead of using this function!encode_noop({47: 11}) == True encode_noop({47: object()}) == False
- Parameters
data (object) – see `encode(...) <pyjson5.encode_>`_
options (Optional[Options]) – see `encode(...) <pyjson5.encode_>`_
options_kw – see `encode(...) <pyjson5.encode_>`_
- Returns
Trueiffdatais serializable.- Return type
- class pyjson5.Options¶
Customizations for the
encoder_*(...)function family.Immutable. Use
Options.update(**kw)to create a new Options instance.- Parameters
str: A special method to call on objects to return a custom JSON encoded string. Must return ASCII data!
False: No such member exists. (Default.)
None: Use default.
posinfinity (str|False|None) –
str: String to represent positive infinity. Must be ASCII.
False: Throw an exception if
float('+inf')is encountered.None: Use default:
"Infinity".
neginfinity (str|False|None) –
str: String to represent negative infinity. Must be ASCII.
False: Throw an exception if
float('-inf')is encountered.None: Use default:
"-Infinity".
str: String to represent not-a-number. Must be ASCII.
False: Throw an exception if
float('NaN')is encountered.None: Use default:
"NaN".
str: Format string to use with
int.False: Throw an exception if an
intis encountered.None: Use default:
"%d".
floatformat (str|False|None) –
str: Format string to use with
float.False: Throw an exception if a
floatis encountered.None: Use default:
"%.6e".
decimalformat (str|False|None) –
str: Format string to use with
Decimal.False: Throw an exception if a
Decimalis encountered.None: Use default:
"%s".
mappingtypes (Iterable[type]|False|None) –
Iterable[type]: Classes the should be encoded to objects. Must be iterable over their keys, and implement
__getitem__.False: There are no objects. Any object will be encoded as list of key-value tuples.
None: Use default:
[collections.abc.Mapping].
- decimalformat¶
The creation argument
decimalformat.NoneifFalsewas specified.
- floatformat¶
The creation argument
floatformat.NoneifFalsewas specified.
- intformat¶
The creation argument
intformat.NoneifFalsewas specified.
- mappingtypes¶
The creation argument
mappingtypes.()ifFalsewas specified.
- nan¶
The creation argument
nan.NoneifFalsewas specified.
- neginfinity¶
The creation argument
neginfinity.NoneifFalsewas specified.
- posinfinity¶
The creation argument
posinfinity.NoneifFalsewas specified.
- tojson¶
The creation argument
tojson.NoneifFalsewas specified.
- update(self, **kw)¶
Creates a new Options instance by modifying some members.
Encoder Compatibility Functions¶
- pyjson5.dump(obj, fp, **kw)¶
Serializes a Python object to a JSON5 compatible unicode string.
Use `encode_io(...) <pyjson5.encode_io_>`_ instead!
dump(obj, fp) == encode_io(obj, fp)
- Parameters
obj (object) – Python object to serialize.
fp (IOBase) – A file-like object to serialize into.
kw – Silently ignored.
- pyjson5.dumps(obj, **kw)¶
Serializes a Python object to a JSON5 compatible unicode string.
Use `encode(...) <pyjson5.encode_>`_ instead!
dumps(obj) == encode(obj)
- Parameters
obj (object) – Python object to serialize.
kw – Silently ignored.
- Returns
see
encode(data)- Return type
unicode
Encoder Exceptions¶

- class pyjson5.Json5EncoderException¶
Base class of any exception thrown by the serializer.
- message¶
Human readable error description
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- class pyjson5.Json5UnstringifiableType(message=None, unstringifiable=None)¶
The encoder was not able to stringify the input, or it was told not to by the supplied
Options.- message¶
Human readable error description
- unstringifiable¶
The value that caused the problem.
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.