Package: jsonlib
Author:John MillikinCopyright:This document has been placed in the public domain.OverviewJSONis a lightweight data-interchange format. It
is often used for exchanging data between a web server and user agent.This module aims to produce a library for serializing and deserializing
JSON that conforms strictly to RFC 4627.For the Python 3 version of jsonlib, seejsonlib-python3.Other JSON implementations of interest includesimplejson(available in the standard library as
of Python 2.6) anddemjson.ContentsOverviewUsageDeserializationFloating-point valuesSerializationPretty-PrintingMapping Key SortingEncoding and UnicodeMapping Key CoercionSerializing Other TypesStreaming SerializerExceptionsReadErrorWriteErrorUnknownSerializerErrorChange Log1.6.11.6Usagejsonlib has two functions of interest,readandwrite. It also
defines some exception:ReadError,WriteError, andUnknownSerializerError.For compatibility with the standard library,readis aliased toloadsandwriteis aliased todumps. They do not have the
same set of advanced parameters, but may be used interchangeably for
simple invocations.DeserializationTo deserialize a JSON expression, call thejsonlib.readfunction with
an instance ofunicodeorbytes.>>> import jsonlib
>>> jsonlib.read (b'["Hello world!"]')
[u'Hello world!']Floating-point valuesBy default,jsonlibwill parse values such as “1.1” into an instance ofdecimal.Decimal. To use the built-in value typefloatinstead, set
theuse_floatparameter toTrue.floatvalues are much faster to
construct, so this flag may substantially increase parser performance.Please note that usingfloatwill cause a loss of precision when
parsing some values.>>> jsonlib.read ('[3.14159265358979323846]', use_float = True)
[3.1415926535897931]SerializationSerialization has more options, but they are set to reasonable defaults.
The simplest use is to calljsonlib.writewith a Python value.>>> import jsonlib
>>> jsonlib.write (['Hello world!'])
'["Hello world!"]'Pretty-PrintingTo “pretty-print” the output, pass a value for theindentparameter.>>> print (jsonlib.write (['Hello world!'], indent = '    ').decode ('utf8'))
[
    "Hello world!"
]
>>>Mapping Key SortingBy default, mapping keys are serialized in whatever order they are
stored by Python. To force a consistent ordering (for example, in doctests)
use thesort_keysparameter.>>> jsonlib.write ({'e': 'Hello', 'm': 'World!'})
'{"m":"World!","e":"Hello"}'
>>> jsonlib.write ({'e': 'Hello', 'm': 'World!'}, sort_keys = True)
'{"e":"Hello","m":"World!"}'Encoding and UnicodeBy default, the output is encoded in UTF-8. If you require a different
encoding, pass the name of a Python codec as theencodingparameter.>>> jsonlib.write (['Hello world!'], encoding = 'utf-16-be')
'\x00[\x00"\x00H\x00e\x00l\x00l\x00o\x00 \x00w\x00o\x00r\x00l\x00d\x00!\x00"\x00]'To retrieve an unencodedunicodeinstance, passNonefor the
encoding.>>> jsonlib.write (['Hello world!'], encoding = None)
u'["Hello world!"]'By default, non-ASCII codepoints are forbidden in the output. To include
higher codepoints in the output, setascii_onlytoFalse.>>> jsonlib.write ([u'Hello \u266a'], encoding = None)
u'["Hello \\u266a"]'
>>> jsonlib.write ([u'Hello \u266a'], encoding = None, ascii_only = False)
u'["Hello \u266a"]'Mapping Key CoercionBecause JSON objects must have string keys, an exception will be raised when
non-string keys are encountered in a mapping. It can be useful to coerce
mapping keys to strings, so thecoerce_keysparameter is available.>>> jsonlib.write ({True: 1})
Traceback (most recent call last):
WriteError: Only strings may be used as object keys.
>>> jsonlib.write ({True: 1}, coerce_keys = True)
'{"True":1}'Serializing Other TypesIf the object implements the iterator or mapping protocol, it will be
handled automatically. If the object is intended for use as a basic value,
it should subclass one of the supported basic values.String-like objects that do not inherit fromunicodeorUserString.UserStringwill likely be serialized as a list. This will
not be changed. If iterating them returns an instance of the same type, the
serializer might crash. This (hopefully) will be changed.To serialize a type not known to jsonlib, use theon_unknownparameter
towrite:>>> from datetime import date
>>> def unknown_handler (value):
...     if isinstance (value, date):
...         return str (value)
...     raise jsonlib.UnknownSerializerError
>>> jsonlib.write ([date (2000, 1, 1)], on_unknown = unknown_handler)
'["2000-01-01"]'Streaming SerializerWhen serializing large objects, the use of an in-memory buffer may cause
too much memory to be used. For these situations, use thedumpfunction
to write objects to a file-like object:>>> import sys
>>> jsonlib.dump (["Written to stdout"], sys.stdout, encoding = None)
["Written to stdout"]
>>> with open ("/dev/null", "wb") as out:
...     jsonlib.dump (["Written to a file"], out)
>>>ExceptionsReadErrorRaised byreadif an error was encountered parsing the expression. Will
contain the line, column, and character position of the error.Note that this will report thecharacter, not thebyte, of the character
that caused the error.WriteErrorRaised bywriteordumpif an error was encountered serializing
the passed value.UnknownSerializerErrorA subclass ofWriteErrorthat is raised when a value cannot be
serialized. See theon_unknownparameter towrite.Change Log1.6.1Fixed error inwrite()which could cause output truncation.1.6Performance improvementscoerce_keysno longer attempts to determine the “JSON” format for
a coerced value – it will simply callunicode().