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#

encode(data, *[, options])

Serializes a Python object as a JSON5 compatible string.

encode_bytes(data, *[, options])

Serializes a Python object to a JSON5 compatible bytes string.

encode_callback(data, cb[, supply_bytes, ...])

Serializes a Python object into a callback function.

encode_io(data, fp[, supply_bytes, options])

Serializes a Python object into a file-object.

encode_noop(data, *[, options])

Test if the input is serializable.

dump(obj, fp, **kw)

Serializes a Python object to a JSON5 compatible string.

dumps(obj, **kw)

Serializes a Python object to a JSON5 compatible string.

Options

Customizations for the encoder_*(...) function family.

Json5EncoderException

Base class of any exception thrown by the serializer.

Json5UnstringifiableType([message, ...])

The encoder was not able to stringify the input, or it was told not to by the supplied Options.

Full Encoder Description#

pyjson5.encode(data, *, options=None, **options_kw)#

Serializes a Python object as a JSON5 compatible string.

encode(['Hello', 'world!']) == '["Hello","world!"]'
Parameters:
  • data (object) – Python object to serialize.

  • options (Optional[Options]) – Extra options for the encoder. If options and options_kw are specified, then options.update(**options_kw) is used.

  • options_kw – See Option’s arguments.

Raises:
Returns:

Unless float('inf') or float('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 escaped.

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:

str

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:
Raises:
Returns:

see encode(…)

Return type:

bytes

pyjson5.encode_callback(data, cb, supply_bytes=False, *, options=None, **options_kw)#

Serializes a Python object into a callback function.

The callback function cb gets called with single characters and strings until the input data is fully serialized.

encode_callback(['Hello', 'world!'], print)
#prints:
# [
# "
# Hello
# "
# ,
# "
# world!
# "
" ]
Parameters:
Raises:
Returns:

The supplied argument cb.

Return type:

Callable[[Union[bytes|str]], None]

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. If fp is unbuffered, then the result will be garbage!

Parameters:
Raises:
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 data directly, and catch exceptions instead of using this function!

encode_noop({47: 11}) == True
encode_noop({47: object()}) == False
Parameters:
Returns:

True iff data is serializable.

Return type:

bool

class pyjson5.Options#

Customizations for the encoder_*(...) function family.

Immutable. Use Options.update(**kw) to create a new Options instance.

Parameters:
  • quotationmark (str|None) –

    • str: One character string that is used to surround strings.

    • None: Use default: '"'.

  • tojson (str|False|None) –

    • 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.

  • mappingtypes (Iterable[type]|False|None) –

    • Iterable[type]: Classes that 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 keys as in list(obj).

    • None: Use default: [collections.abc.Mapping].

mappingtypes#

The creation argument mappingtypes. () if False was specified.

quotationmark#

The creation argument quotationmark.

tojson#

The creation argument tojson. None if False was specified.

update(self, *args, **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 string.

Use 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 string.

Use encode(…) instead!

dumps(obj) == encode(obj)
Parameters:
  • obj (object) – Python object to serialize.

  • kw – Silently ignored.

Returns:

see encode(…)

Return type:

str

Encoder Exceptions#

digraph inheritanceddce59db82 { bgcolor=transparent; fontsize=32; rankdir=LR; size="6.0, 8.0"; "pyjson5.pyjson5.Json5EncoderException" [URL="#pyjson5.Json5EncoderException",color=black,fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="filled,solid",target="_top",tooltip="Base class of any exception thrown by the serializer."]; "pyjson5.pyjson5.Json5Exception" -> "pyjson5.pyjson5.Json5EncoderException" [arrowsize=0.8,penwidth=1.2,style="setlinewidth(0.5)"]; "pyjson5.pyjson5.Json5Exception" [URL="exceptions.html#pyjson5.Json5Exception",color=black,fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="filled,solid",target="_top",tooltip="Json5Exception(message=None, *args)"]; "pyjson5.pyjson5.Json5UnstringifiableType" [URL="#pyjson5.Json5UnstringifiableType",color=black,fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="filled,solid",target="_top",tooltip="Json5UnstringifiableType(message=None, unstringifiable=None)"]; "pyjson5.pyjson5.Json5EncoderException" -> "pyjson5.pyjson5.Json5UnstringifiableType" [arrowsize=0.8,penwidth=1.2,style="setlinewidth(0.5)"]; }
exception pyjson5.Json5EncoderException#

Base class of any exception thrown by the serializer.

add_note()#

Exception.add_note(note) – add a note to the exception

message#

Human readable error description

with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception 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.

add_note()#

Exception.add_note(note) – add a note to the exception

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.