json is simplejson, added to the stdlib. But since json was added in 2.6, simplejson has the advantage of working on more Python versions (2.4+).

simplejson is also updated more frequently than Python, so if you need (or want) the latest version, it's best to use simplejson itself, if possible.

A good practice, in my opinion, is to use one or the other as a fallback.

try:
    import simplejson as json
except ImportError:
    import json
Answer from Devin Jeanpierre on Stack Overflow
🌐
GitHub
github.com › simplejson › simplejson
GitHub - simplejson/simplejson: simplejson is a simple, fast, extensible JSON encoder/decoder for Python · GitHub
simplejson is a simple, fast, complete, correct and extensible JSON <http://json.org> encoder and decoder for Python 3.3+ with legacy support for Python 2.5+. It is pure Python code with no dependencies, but includes an optional C extension ...
Starred by 1.7K users
Forked by 355 users
Languages   Python 61.7% | C 38.3%
🌐
Readthedocs
simplejson.readthedocs.io
simplejson — JSON encoder and decoder — simplejson 3.19.1 documentation
Decode a JSON document from s (a str or unicode beginning with a JSON document) starting from the index idx and return a 2-tuple of the Python representation and the index in s where the document ended. This can be used to decode a JSON document from a string that may have extraneous data at the end, or to decode a string that has a series of JSON objects. JSONDecodeError will be raised if the given JSON document is not valid. class simplejson.JSONEncoder(skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=False, sort_keys=False, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, item_sort_key=None, for_json=True, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False)¶
🌐
PyPI
pypi.org › project › simplejson
simplejson · PyPI
simplejson-3.20.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl (150.6 kB view details)
      » pip install simplejson
    
Published   Sep 26, 2025
Version   3.20.2
🌐
ZetCode
zetcode.com › python › simplejson
Python simplejson - read, write JSON in Python with simplejson
January 29, 2024 - With the help of Python's format method, we print the retrieved data to the console. $ ./parse_json_url.py Unix time: 1691507071395 Time: 03:04:31 PM Date: 08-08-2023 · With simplejson we can easily pretty print our data.
🌐
Web2py
web2py.com › examples › static › sphinx › gluon › gluon.contrib.simplejson.html
Simplejson Documentation — Web2Py v1.64.4 documentation
It is the externally maintained version of the json library contained in Python 2.6, but maintains compatibility with Python 2.4 and Python 2.5 and (currently) has significant performance advantages, even without using the optional C extension for speedups. ... >>> import simplejson as json >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) '["foo", {"bar": ["baz", null, 1.0, 2]}]' >>> print json.dumps("\"foo\bar") "\"foo\bar" >>> print json.dumps(u'\u1234') "\u1234" >>> print json.dumps('\\') "\\" >>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True) {"a": 0, "b": 0, "c": 0} >>> from StringIO import StringIO >>> io = StringIO() >>> json.dump(['streaming API'], io) >>> io.getvalue() '["streaming API"]'
🌐
Readthedocs
simplejson.readthedocs.io › en › v3.16.1
simplejson — JSON encoder and decoder — simplejson 3.16.1 documentation
Decode a JSON document from s (a str or unicode beginning with a JSON document) starting from the index idx and return a 2-tuple of the Python representation and the index in s where the document ended. This can be used to decode a JSON document from a string that may have extraneous data at the end, or to decode a string that has a series of JSON objects. JSONDecodeError will be raised if the given JSON document is not valid. class simplejson.JSONEncoder(skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, item_sort_key=None, for_json=True, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False)¶
Top answer
1 of 14
425

json is simplejson, added to the stdlib. But since json was added in 2.6, simplejson has the advantage of working on more Python versions (2.4+).

simplejson is also updated more frequently than Python, so if you need (or want) the latest version, it's best to use simplejson itself, if possible.

A good practice, in my opinion, is to use one or the other as a fallback.

try:
    import simplejson as json
except ImportError:
    import json
2 of 14
89

I have to disagree with the other answers: the built in json library (in Python 2.7) is not necessarily slower than simplejson. It also doesn't have this annoying unicode bug.

Here is a simple benchmark:

import json
import simplejson
from timeit import repeat

NUMBER = 100000
REPEAT = 10

def compare_json_and_simplejson(data):
    """Compare json and simplejson - dumps and loads"""
    compare_json_and_simplejson.data = data
    compare_json_and_simplejson.dump = json.dumps(data)
    assert json.dumps(data) == simplejson.dumps(data)
    result = min(repeat("json.dumps(compare_json_and_simplejson.data)", "from __main__ import json, compare_json_and_simplejson", 
                 repeat = REPEAT, number = NUMBER))
    print "      json dumps {} seconds".format(result)
    result = min(repeat("simplejson.dumps(compare_json_and_simplejson.data)", "from __main__ import simplejson, compare_json_and_simplejson", 
                 repeat = REPEAT, number = NUMBER))
    print "simplejson dumps {} seconds".format(result)
    assert json.loads(compare_json_and_simplejson.dump) == data
    result = min(repeat("json.loads(compare_json_and_simplejson.dump)", "from __main__ import json, compare_json_and_simplejson", 
                 repeat = REPEAT, number = NUMBER))
    print "      json loads {} seconds".format(result)
    result = min(repeat("simplejson.loads(compare_json_and_simplejson.dump)", "from __main__ import simplejson, compare_json_and_simplejson", 
                 repeat = REPEAT, number = NUMBER))
    print "simplejson loads {} seconds".format(result)


print "Complex real world data:" 
COMPLEX_DATA = {'status': 1, 'timestamp': 1362323499.23, 'site_code': 'testing123', 'remote_address': '212.179.220.18', 'input_text': u'ny monday for less than \u20aa123', 'locale_value': 'UK', 'eva_version': 'v1.0.3286', 'message': 'Successful Parse', 'muuid1': '11e2-8414-a5e9e0fd-95a6-12313913cc26', 'api_reply': {"api_reply": {"Money": {"Currency": "ILS", "Amount": "123", "Restriction": "Less"}, "ProcessedText": "ny monday for less than \\u20aa123", "Locations": [{"Index": 0, "Derived From": "Default", "Home": "Default", "Departure": {"Date": "2013-03-04"}, "Next": 10}, {"Arrival": {"Date": "2013-03-04", "Calculated": True}, "Index": 10, "All Airports Code": "NYC", "Airports": "EWR,JFK,LGA,PHL", "Name": "New York City, New York, United States (GID=5128581)", "Latitude": 40.71427, "Country": "US", "Type": "City", "Geoid": 5128581, "Longitude": -74.00597}]}}}
compare_json_and_simplejson(COMPLEX_DATA)
print "\nSimple data:"
SIMPLE_DATA = [1, 2, 3, "asasd", {'a':'b'}]
compare_json_and_simplejson(SIMPLE_DATA)

And the results on my system (Python 2.7.4, Linux 64-bit):

Complex real world data:
json dumps 1.56666707993 seconds
simplejson dumps 2.25638604164 seconds
json loads 2.71256899834 seconds
simplejson loads 1.29233884811 seconds

Simple data:
json dumps 0.370109081268 seconds
simplejson dumps 0.574181079865 seconds
json loads 0.422876119614 seconds
simplejson loads 0.270955085754 seconds

For dumping, json is faster than simplejson. For loading, simplejson is faster.

Since I am currently building a web service, dumps() is more important—and using a standard library is always preferred.

Also, cjson was not updated in the past 4 years, so I wouldn't touch it.

🌐
Snyk
snyk.io › advisor › simplejson › simplejson code examples
Top 5 simplejson Code Examples | Snyk
def _import_speedups(): try: from simplejson import _speedups return _speedups.encode_basestring_ascii, _speedups.make_encoder except ImportError: return None, None · Simple, fast, extensible JSON encoder/decoder for Python
Find elsewhere
🌐
BuildBot
docs.buildbot.net › 0.8.7 › reference › simplejson-module.html
Package simplejson
>>> import simplejson as json >>> def as_complex(dct): ... if '__complex__' in dct: ... return complex(dct['real'], dct['imag']) ... return dct ... >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}', ...
🌐
Red-bean
svn.red-bean.com › bob › simplejson › tags › simplejson-1.3 › docs › index.html
simplejson -- A simple, fast, extensible JSON encoder and decoder
>>> import simplejson >>> simplejson.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) '["foo", {"bar": ["baz", null, 1.0, 2]}]' >>> print simplejson.dumps("\"foo\bar") "\"foo\bar" >>> print simplejson.dumps(u'\u1234') "\u1234" >>> print simplejson.dumps('\\') "\\" >>> print simplejson.dumps({"c": ...
🌐
CloudDefense.ai
clouddefense.ai › code › python › example › simplejson
Top 10 Examples of <!-- -->simplejson<!-- --> code in Python | CloudDefense.AI
def _toggle_speedups(enabled): import simplejson.decoder as dec import simplejson.encoder as enc import simplejson.scanner as scan c_make_encoder = _import_c_make_encoder() if enabled: dec.scanstring = dec.c_scanstring or dec.py_scanstring enc.c_make_encoder = c_make_encoder enc.encode_basestring_ascii = (enc.c_encode_basestring_ascii or enc.py_encode_basestring_ascii) scan.make_scanner = scan.c_make_scanner or scan.py_make_scanner else: dec.scanstring = dec.py_scanstring enc.c_make_encoder = None enc.encode_basestring_ascii = enc.py_encode_basestring_ascii scan.make_scanner = scan.py_make_scanner dec.make_scanner = scan.make_scanner global _default_decoder _default_decoder = JSONDecoder( encoding=None, object_hook=None, object_pairs_hook=None, ) global _default_encoder _default_encoder = JSONEncoder( skipkeys=False, ensure_ascii=True,
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-install-simplejson-package-for-python
How to Install SimpleJson Package for Python? - GeeksforGeeks
June 3, 2022 - In protocols such as JSON-RPC, which have a more comprehensive type system than JSON itself. In this article, we will cover how we can install simplejson in different ways: Step 1: Open the command prompt in administrator mode. Step 2: Check whether Python is installed on your computer or not ...
Top answer
1 of 7
30

I've used this strategy in the past and been pretty happy with it: Encode your custom objects as JSON object literals (like Python dicts) with the following structure:

{ '__ClassName__': { ... } }

That's essentially a one-item dict whose single key is a special string that specifies what kind of object is encoded, and whose value is a dict of the instance's attributes. If that makes sense.

A very simple implementation of an encoder and a decoder (simplified from code I've actually used) is like so:

TYPES = { 'ParentClass': ParentClass,
          'ChildClass': ChildClass }


class CustomTypeEncoder(json.JSONEncoder):
    """A custom JSONEncoder class that knows how to encode core custom
    objects.

    Custom objects are encoded as JSON object literals (ie, dicts) with
    one key, '__TypeName__' where 'TypeName' is the actual name of the
    type to which the object belongs.  That single key maps to another
    object literal which is just the __dict__ of the object encoded."""

    def default(self, obj):
        if isinstance(obj, TYPES.values()):
            key = '__%s__' % obj.__class__.__name__
            return { key: obj.__dict__ }
        return json.JSONEncoder.default(self, obj)


def CustomTypeDecoder(dct):
    if len(dct) == 1:
        type_name, value = dct.items()[0]
        type_name = type_name.strip('_')
        if type_name in TYPES:
            return TYPES[type_name].from_dict(value)
    return dct

In this implementation assumes that the objects you're encoding will have a from_dict() class method that knows how to take recreate an instance from a dict decoded from JSON.

It's easy to expand the encoder and decoder to support custom types (e.g. datetime objects).

EDIT, to answer your edit: The nice thing about an implementation like this is that it will automatically encode and decode instances of any object found in the TYPES mapping. That means that it will automatically handle a ChildClass like so:

class ChildClass(object):
    def __init__(self):
        self.foo = 'foo'
        self.bar = 1.1
        self.parent = ParentClass(1)

That should result in JSON something like the following:

{ '__ChildClass__': {
    'bar': 1.1,
    'foo': 'foo',
    'parent': {
        '__ParentClass__': {
            'foo': 1}
        }
    }
}
2 of 7
10

An instance of a custom class could be represented as JSON formatted string with help of following function:

def json_repr(obj):
  """Represent instance of a class as JSON.
  Arguments:
  obj -- any object
  Return:
  String that reprent JSON-encoded object.
  """
  def serialize(obj):
    """Recursively walk object's hierarchy."""
    if isinstance(obj, (bool, int, long, float, basestring)):
      return obj
    elif isinstance(obj, dict):
      obj = obj.copy()
      for key in obj:
        obj[key] = serialize(obj[key])
      return obj
    elif isinstance(obj, list):
      return [serialize(item) for item in obj]
    elif isinstance(obj, tuple):
      return tuple(serialize([item for item in obj]))
    elif hasattr(obj, '__dict__'):
      return serialize(obj.__dict__)
    else:
      return repr(obj) # Don't know how to handle, convert to string
  return json.dumps(serialize(obj))

This function will produce JSON-formatted string for

  • an instance of a custom class,

  • a dictionary that have instances of custom classes as leaves,

  • a list of instances of custom classes
🌐
TutorialsPoint
tutorialspoint.com › What-are-the-differences-between-json-and-simplejson-Python-modules
What are the differences between json and simplejson Python modules?
simplejson is also updated more frequently than Python. Although they are the same, the version included in the stdlib doesn't include the latest optimizations. So if you need (or want) the latest version, it's best to use simplejson itself, if possible. A good practice, is to use one or the other as a fallback. For example...
🌐
pkimber.net
pkimber.net › howto › python › json › simplejson.html
JSON — pkimber.net - Python
Joy of Python: Classes and Dictionaries, all the attributes in a class are already in a __dict__… ... import simplejson # or json for python 2.6 f = open('out.json', 'wb') data = # create a list/dictionary etc...
🌐
Programiz
programiz.com › python-programming › json
Python JSON: Read, Write, Parse JSON (With Examples)
Python simplejson · What is JSON? Using json Module · Parse JSON in Python · Example: JSON string to dict · Example: Python read JSON file · dict to JSON string (with Example) Writing JSON to a file (with Example) Pretty print JSON (with Example) Previous Tutorial: Python Asserts ·
🌐
Anaconda.org
anaconda.org › conda-forge › simplejson
simplejson - conda-forge | Anaconda.org
Install simplejson with Anaconda.org. Simple, fast, extensible JSON encoder/decoder for Python
🌐
SourceForge
sourceforge.net › projects › simplejson.mirror
simplejson download | SourceForge.net
September 24, 2025 - Download simplejson for free. simplejson is a simple, fast, extensible JSON encoder/decoder . simplejson is a simple, fast, complete, correct and extensible JSON encoder and decoder for Python 3.3+ with legacy support for Python 2.5+. It is pure Python code with no dependencies but includes ...