Skip to main content

JSON serializer/deserializer for Python

Project description

Author: John Millikin
Copyright: This document has been placed in the public domain.


JSON is 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.


jsonlib has two functions of interest, read and write. It also defines some exception: ReadError, WriteError, and UnknownSerializerError.


To deserialize a JSON expression, call the function with an instance of str or unicode.

>>> import jsonlib
>>> ('["Hello world!"]')
[u'Hello world!']


Serialization has more options, but they are set to reasonable defaults. The simplest use is to call jsonlib.write with a Python value.

>>> import jsonlib
>>> jsonlib.write (['Hello world!'])
'["Hello world!"]'


To “pretty-print” the output, pass a value for the indent parameter.

>>> print jsonlib.write (['Hello world!'], indent = '    ')
    "Hello world!"

Mapping Key Sorting

By default, mapping keys are serialized in whatever order they are stored by Python. To force a consistent ordering (for example, in doctests) use the sort_keys parameter.

>>> jsonlib.write ({'e': 'Hello', 'm': 'World!'})
>>> jsonlib.write ({'e': 'Hello', 'm': 'World!'}, sort_keys = True)

Encoding and Unicode

By default, the output is encoded in UTF-8. If you require a different encoding, pass the name of a Python codec as the encoding parameter.

>>> 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 unencoded unicode instance, pass None for 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, set ascii_only to False.

>>> 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 Coercion

Because 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 the coerce_keys parameter 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)

Serializing Other Types

If 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 from str, unicode, or UserString.UserString will 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 the on_unknown parameter to write:

>>> 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)

Streaming Serializer

When serializing large objects, the use of an in-memory buffer may cause too much memory to be used. For these situations, use the dump function to write objects to a file-like object:

>>> import sys
>>> jsonlib.dump (["Written to stdout"], sys.stdout)
["Written to stdout"]



Raised by read if an error was encountered parsing the expression. Will contain the line, column, and character position of the error.

Note that this will report the character, not the byte, of the character that caused the error.


Raised by write or dump if an error was encountered serializing the passed value.


A subclass of WriteError that is raised when a value cannot be serialized. See the on_unknown parameter to write.

Change Log


  • If an unterminated object or array is encountered, report its start location properly.
  • Improved reporting of unknown escape codes.
  • Raise an exception when parsing a root value that is not an array or object.
  • Allow instances of UserString to be used as object keys.
  • Implemented the dump() function.

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Filename, size & hash SHA256 hash help File type Python version Upload date
jsonlib-1.3.6-py2.4-linux-i686.egg (41.5 kB) Copy SHA256 hash SHA256 Egg 2.4
jsonlib-1.3.6-py2.4-macosx-10.3-fat.egg (32.2 kB) Copy SHA256 hash SHA256 Egg 2.4
jsonlib-1.3.6-py2.4-win32.egg (18.3 kB) Copy SHA256 hash SHA256 Egg 2.4
jsonlib-1.3.6-py2.5-linux-i686.egg (41.5 kB) Copy SHA256 hash SHA256 Egg 2.5
jsonlib-1.3.6-py2.5-macosx-10.3-i386.egg (19.2 kB) Copy SHA256 hash SHA256 Egg 2.5
jsonlib-1.3.6-py2.5-win32.egg (18.1 kB) Copy SHA256 hash SHA256 Egg 2.5
jsonlib-1.3.6.tar.gz (19.2 kB) Copy SHA256 hash SHA256 Source None
jsonlib-1.3.6.win32-py2.4.exe (89.5 kB) Copy SHA256 hash SHA256 Windows Installer 2.4
jsonlib-1.3.6.win32-py2.5.exe (89.5 kB) Copy SHA256 hash SHA256 Windows Installer 2.5

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN SignalFx SignalFx Supporter DigiCert DigiCert EV certificate StatusPage StatusPage Status page