Python simplejson
last modified November 18, 2026 Python 3.15
In this article we show how to read and write JSON data with the Python simplejson library.
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It
is easily read and written by humans and parsed and generated by machines. The
application/json is the official Internet media type for JSON. The
JSON filename extension is .json.
The simplejson library
simplejson is a fast, complete, and extensible JSON encoder and
decoder. It is the externally maintained development version of the
json module, which was added to the standard library in Python
2.6. The library is pure Python with an optional C extension for speed; wheels
with the C extension are available for all common platforms.
The API is the same as that of the standard json module, so
simplejson can be used as a drop-in replacement. On top of that, it supports
Decimal numbers, named tuples, the for_json
protocol, pre-encoded RawJSON fragments, and several options for
JavaScript clients. It is also released independently of Python, so its fixes
and features come sooner.
Unlike json, simplejson is not part of the standard library and
must be installed.
$ pip install simplejson
Version
By convention, the library is imported under the name json, so
that code written for the standard module works without changes.
import sys import simplejson as json print(json.__version__) print(sys.version)
We print the version of simplejson and of Python. The examples in this article use simplejson 4.3; version 4 requires Python 3.9 or later (or the legacy Python 2.7).
$ python version.py 4.3.0 3.15.2 (main, Oct 26 2026, 14:06:56) [Clang 23.1.3 ]
Conversion table
The following table shows how data types are converted between Python and JSON by simplejson.
| Python | JSON |
|---|---|
| dict, namedtuple | object |
| list, tuple | array |
| str | string |
| int, float, Decimal | number |
| True | true |
| False | false |
| None | null |
Decoding goes the other way; JSON arrays become lists and JSON numbers
become int or float, or Decimal on
request. Dictionary keys in JSON are always strings, so non-string keys such
as integers come back as strings.
Serializing to a string with dumps
The dumps function serializes a Python object to a JSON
formatted string.
import simplejson as json
data = [{'name': 'Jane', 'age': 17, 'student': True, 'phone': None},
{'name': 'Thomas', 'age': 27, 'student': False, 'phone': '0905'}]
json_data = json.dumps(data)
print(type(json_data))
print(json_data)
We serialize a list of dictionaries. Python's True,
False, and None become JSON's true,
false, and null.
$ python json_dumps.py
<class 'str'>
[{"name": "Jane", "age": 17, "student": true, "phone": null}, {"name": "Thomas", "age": 27, "student": false, "phone": "0905"}]
Writing to a file with dump
The dump function serializes a Python object as a JSON
formatted stream to a file object.
import simplejson as json
data = {'name': 'Jane', 'age': 17, 'city': 'Bratislava'}
with open('friends.json', 'w', encoding='utf-8') as f:
json.dump(data, f)
with open('friends.json', encoding='utf-8') as f:
print(f.read())
We write a dictionary to the friends.json file and read the
file back to show its contents. JSON text should be encoded in UTF-8, so we
open the file with this encoding.
$ python json_dump.py
{"name": "Jane", "age": 17, "city": "Bratislava"}
Deserializing a string with loads
The loads function deserializes a JSON document from a string
or bytes object to a Python object.
import simplejson as json
json_data = '{"name": "Jane", "age": 17, "langs": ["sk", "en"], "pet": null}'
data = json.loads(json_data)
print(type(data))
print(data)
print(data['langs'][1])
The JSON object becomes a Python dictionary, the array a list, and
null becomes None.
$ python json_loads.py
<class 'dict'>
{'name': 'Jane', 'age': 17, 'langs': ['sk', 'en'], 'pet': None}
en
Reading a file with load
The load function deserializes a JSON document from a file
object. We have a configuration file.
{
"theme": "bluespring",
"size": "small",
"splashscreen": false,
"recent": ["notes.txt", "todo.md"]
}
The file contains a string, a boolean, and an array.
import simplejson as json
with open('config.json', encoding='utf-8') as f:
config = json.load(f)
print(f"Theme: {config['theme']}")
print(f"Size: {config['size']}")
print(f"Splash screen: {config['splashscreen']}")
print(f"Recent files: {', '.join(config['recent'])}")
We read the configuration with load and print its values. JSON
false is converted to Python False.
$ python read_config.py Theme: bluespring Size: small Splash screen: False Recent files: notes.txt, todo.md
Pretty printing
The indent option produces indented, human-readable output. The
separators option makes the output as compact as possible.
import simplejson as json
car = {'name': 'Audi', 'model': 2012, 'price': 22000,
'colours': ['gray', 'red', 'white']}
print(json.dumps(car, indent=4, sort_keys=True))
print(json.dumps(car, separators=(',', ':')))
With indent=4, every element is on its own line, indented by
four spaces per level; sort_keys=True sorts the keys of the
objects. The (',', ':') separators remove the spaces after the
commas and colons. Since simplejson 4.1, the C extension also speeds up
indented output.
$ python pretty_print.py
{
"colours": [
"gray",
"red",
"white"
],
"model": 2012,
"name": "Audi",
"price": 22000
}
{"name":"Audi","model":2012,"price":22000,"colours":["gray","red","white"]}
Non-ASCII text
By default, non-ASCII characters are written as \uXXXX
escapes. With ensure_ascii=False, they are written as they are.
import simplejson as json
city = {'name': 'Košice', 'country': 'Slovensko'}
print(json.dumps(city))
print(json.dumps(city, ensure_ascii=False))
data = json.loads(b'{"name": "Ko\\u0161ice"}')
print(data)
Both forms are valid JSON and decode to the same string. The
loads function also accepts bytes, which it decodes as UTF-8.
$ python unicode_text.py
{"name": "Ko\u0161ice", "country": "Slovensko"}
{"name": "Košice", "country": "Slovensko"}
{'name': 'Košice'}
Decimal numbers
Floating-point numbers cannot represent most decimal fractions exactly. For
money and other exact values, Python has the Decimal type, and
simplejson supports it in both directions.
from decimal import Decimal
import simplejson as json
order = {'item': 'book', 'price': Decimal('19.90'), 'qty': 3}
print(json.dumps(order))
data = json.loads('{"price": 19.90, "rate": 0.1}', use_decimal=True)
print(data)
print(data['price'] * 3)
data = json.loads('{"price": 19.90, "rate": 0.1}')
print(data, data['rate'] * 3)
The use_decimal option is on by default in dumps,
so a Decimal is written as a JSON number with all its digits,
including the trailing zero.
data = json.loads('{"price": 19.90, "rate": 0.1}', use_decimal=True)
When decoding, we must ask for Decimal numbers with
use_decimal=True. Arithmetic with them is exact; with floats,
0.1 times three is not exactly 0.3.
$ python decimals.py
{"item": "book", "price": 19.90, "qty": 3}
{'price': Decimal('19.90'), 'rate': Decimal('0.1')}
59.70
{'price': 19.9, 'rate': 0.1} 0.30000000000000004
Decimal with the json module
For comparison, the standard json module cannot serialize
Decimal values.
from decimal import Decimal
import json
order = {'item': 'book', 'price': Decimal('19.90'), 'qty': 3}
try:
print(json.dumps(order))
except TypeError as e:
print(e)
print(e.__notes__)
print(json.dumps(order, default=str))
The standard module raises a TypeError. Since Python 3.14, the
exception carries notes that say where in the data the problem occurred. A
default function can convert the value, but here it becomes a
JSON string instead of a number. To decode numbers as Decimal,
the standard module needs parse_float=Decimal.
$ python decimals_json.py
Object of type Decimal is not JSON serializable
["when serializing dict item 'price'"]
{"item": "book", "price": "19.90", "qty": 3}
Named tuples
simplejson serializes named tuples as JSON objects, using the field names as keys. The standard module writes them as arrays.
from collections import namedtuple
import simplejson as json
Point = namedtuple('Point', 'x y')
points = [Point(1, 2), Point(3, 4)]
print(json.dumps(points))
print(json.dumps(points, namedtuple_as_object=False))
print(json.dumps({'origin': (0, 0)}))
The namedtuple_as_object option controls this behaviour; when
it is false, named tuples are written as plain arrays. Ordinary tuples are
always written as arrays.
$ python namedtuples.py
[{"x": 1, "y": 2}, {"x": 3, "y": 4}]
[[1, 2], [3, 4]]
{"origin": [0, 0]}
NaN and infinity
The JSON standard has no representation for NaN and infinity. simplejson
rejects them by default, while the standard module writes the
non-standard NaN and Infinity tokens.
import simplejson as json
vals = [1.5, float('nan'), float('inf')]
try:
json.dumps(vals)
except ValueError as e:
print(e)
print(json.dumps(vals, ignore_nan=True))
print(json.dumps(vals, allow_nan=True))
try:
json.loads('[1.5, NaN]')
except json.JSONDecodeError as e:
print(e)
print(json.loads('[1.5, NaN]', allow_nan=True))
With the default allow_nan=False, encoding NaN raises a
ValueError. The ignore_nan option writes
null instead, which is what JavaScript's
JSON.stringify does. allow_nan=True writes the
JavaScript literals, which many JSON parsers do not accept. The decoder
rejects these tokens by default too.
$ python nan_values.py Out of range float values are not JSON compliant: nan [1.5, null, null] [1.5, NaN, Infinity] Expecting value: line 1 column 7 (char 6) [1.5, nan]
Big integers
JavaScript numbers are double-precision floats; integers above 253 lose precision when a browser parses them. simplejson can write such integers as strings.
import simplejson as json
ids = {'small': 42, 'tweet_id': 1460323737035677698}
print(json.dumps(ids))
print(json.dumps(ids, int_as_string_bitcount=53))
print(json.dumps(ids, bigint_as_string=True))
print(json.loads('{"id": 1460323737035677698}'))
The int_as_string_bitcount option writes integers that need
more than the given number of bits as strings; bigint_as_string
is a shortcut for a 53-bit limit. Small integers stay numbers. Python itself
has no such limit: the decoder reads the big number exactly.
$ python big_ints.py
{"small": 42, "tweet_id": 1460323737035677698}
{"small": 42, "tweet_id": "1460323737035677698"}
{"small": 42, "tweet_id": "1460323737035677698"}
{'id': 1460323737035677698}
Decoding errors
Invalid JSON raises JSONDecodeError, which tells us where the
problem is.
import simplejson as json
bad = '''{
"name": "Jane",
"age": 17,
}'''
try:
json.loads(bad)
except json.JSONDecodeError as e:
print(e)
print(f'msg={e.msg!r} line={e.lineno} col={e.colno} pos={e.pos}')
print(isinstance(e, ValueError))
JSON does not allow a trailing comma. The exception has the
msg, lineno, colno, and
pos attributes. It is a subclass of ValueError, so
code that catches ValueError handles it too.
$ python decode_error.py Illegal trailing comma before end of object: line 3 column 14 (char 35) msg='Illegal trailing comma before end of object' line=3 col=14 pos=35 True
Decoding hooks
Hooks post-process the decoded data. The object_hook is called
for every decoded JSON object, and the array_hook for every
array.
from datetime import date
import simplejson as json
text = '''[
{"name": "Jane", "born": "2009-03-14", "tags": ["a", "b"]},
{"name": "Paul", "born": "1997-11-02", "tags": []}
]'''
def to_date(obj):
if 'born' in obj:
obj['born'] = date.fromisoformat(obj['born'])
return obj
people = json.loads(text, object_hook=to_date)
for p in people:
print(p['name'], p['born'], p['born'].year)
print(json.loads(text, array_hook=tuple)[0]['tags'])
The to_date hook turns the ISO 8601 date strings into
date objects. The array_hook option, new in
simplejson 4, replaces every list with the value returned by the hook; here we
get tuples. The standard json module gained the same option in
Python 3.15.
$ python hooks.py
Jane 2009-03-14 2009
Paul 1997-11-02 1997
('a', 'b')
Custom objects with for_json
Custom objects are not serializable by default. With the
for_json=True option, simplejson calls the object's
for_json method and serializes the value it returns.
from datetime import date
import simplejson as json
class Person:
def __init__(self, name, born):
self.name = name
self.born = born
def for_json(self):
return {'name': self.name, 'born': self.born.isoformat()}
people = [Person('Lucy', date(1998, 5, 3)), Person('Thomas', date(1995, 1, 21))]
print(json.dumps(people, for_json=True, indent=2))
The for_json method returns a dictionary with the date in ISO
format. The class decides how it is represented, and the call to
dumps stays simple.
$ python custom_class.py
[
{
"name": "Lucy",
"born": "1998-05-03"
},
{
"name": "Thomas",
"born": "1995-01-21"
}
]
The default function
The default function is called for objects that cannot be
serialized otherwise; it must return a serializable value or raise
TypeError. It works with classes we cannot modify.
from dataclasses import dataclass, asdict, is_dataclass
from datetime import datetime
import simplejson as json
@dataclass
class Event:
title: str
start: datetime
tags: set
def encode(obj):
if is_dataclass(obj):
return asdict(obj)
if isinstance(obj, datetime):
return obj.isoformat()
if isinstance(obj, set):
return sorted(obj)
raise TypeError(f'Cannot serialize {type(obj).__name__}')
ev = Event('PyCon', datetime(2026, 5, 13, 9, 30), {'python', 'conf'})
print(json.dumps(ev, default=encode))
try:
json.dumps(object(), default=encode)
except TypeError as e:
print(e)
The function converts data classes to dictionaries, datetimes to ISO
strings, and sets to sorted lists. For other types, it raises a
TypeError, which propagates from dumps.
$ python default_fun.py
{"title": "PyCon", "start": "2026-05-13T09:30:00", "tags": ["conf", "python"]}
Cannot serialize object
Embedding pre-encoded JSON
A RawJSON object holds a string that is already valid JSON. It
is inserted into the output as it is, without decoding and encoding it
again.
import simplejson as json
cached = '{"lat": 48.1486, "lon": 17.1077}'
data = {'city': 'Bratislava', 'location': json.RawJSON(cached)}
print(json.dumps(data))
This is useful for JSON fragments stored in a cache or a database column. simplejson does not validate the raw string, so it must be valid JSON.
$ python raw_json.py
{"city": "Bratislava", "location": {"lat": 48.1486, "lon": 17.1077}}
JSON in HTML
JSON embedded in an HTML script element must not contain the
</script> sequence. JSONEncoderForHTML
escapes the <, >, and &
characters.
import simplejson as json
data = {'comment': '</script><script>alert("hi")</script>'}
print(json.dumps(data))
print(json.JSONEncoderForHTML().encode(data))
The plain output would end the script element early and allow the injection of another script. The escaped output is still valid JSON and decodes to the same string.
$ python html_safe.py
{"comment": "</script><script>alert(\"hi\")</script>"}
{"comment": "\u003c/script\u003e\u003cscript\u003ealert(\"hi\")\u003c/script\u003e"}
Reading JSON from a URL
The following example reads JSON data from a web service. We use the free JSONPlaceholder API.
import urllib.request
import simplejson as json
url = 'https://jsonplaceholder.typicode.com/todos?userId=1&_limit=3'
req = urllib.request.Request(url, headers={'User-Agent': 'zetcode-example'})
with urllib.request.urlopen(req, timeout=10) as res:
todos = json.load(res)
for todo in todos:
mark = 'x' if todo['completed'] else ' '
print(f"[{mark}] {todo['id']}: {todo['title']}")
We create a request with urllib.request and pass the response,
which is a file-like object, directly to load. The
timeout prevents the program from waiting forever if the server
does not respond.
$ python fetch_url.py [ ] 1: delectus aut autem [ ] 2: quis ut nam facilis et officia qui [ ] 3: fugiat veniam minus
Source
In this article we have worked with JSON data using the simplejson library. See also Python Decimal, Python namedtuple, Python dataclass, and Python pickle.
Author
List all Python tutorials.