Python Read, Write, Parse JSON (with examples)

JSON, Javascript Object Notation, is a lightweight data interchange format inspired by Javascript object literal syntax.

In this article, you’ll learn how to work with JSON data in Python.

Python has a built-in package called json, which can be used to encode and decode json data.

Python JSON encoding/marshaling

Python’s json.dumps() function allows you to serialize or encode a Python type like dict, list, etc; to json string. Here is how you can use it -

import json

user = {
  "name": "Rajeev Singh",
  "age": 26,
  "hobbies": ["Coding", "Travelling", "Photography"],
  "address": {
    "city": "Bangalore",
    "state": "Karnataka",
    "country": "India"
  }
}

jsonData = json.dumps(user)
print(jsonData)
# Output
{"name": "Rajeev Singh", "age": 26, "hobbies": ["Coding", "Travelling", "Photography"], "address": {"city": "Bangalore", "state": "Karnataka", "country": "India"}}

Setting custom options while JSON encoding

You can set custom options like indent and sort_keys to customize the output of json.dumps() method:

import json

user = {
  "name": "Rajeev Singh",
  "age": 26,
  "hobbies": ["Coding", "Travelling", "Photography"],
  "address": {
    "city": "Bangalore",
    "state": "Karnataka",
    "country": "India"
  }
}

jsonData = json.dumps(user, sort_keys=True, indent=4)
print(jsonData)
# Output
{
    "address": {
        "city": "Bangalore",
        "country": "India",
        "state": "Karnataka"
    },
    "age": 26,
    "hobbies": [
        "Coding",
        "Travelling",
        "Photography"
    ],
    "name": "Rajeev Singh"
}

Python JSON decoding/parsing

You can decode a JSON string in Python using the json.loads() function -

import json

jsonData = '{"name": "Sachin Tendulkar", "age": 34, "hobbies": ["Cricket", "Badminton"], "address": {"city": "Mumbai", "state": "Maharastra", "country": "India"}}'

user = json.loads(jsonData)
print(user)
# Output
{'name': 'Sachin Tendulkar', 'age': 34, 'hobbies': ['Cricket', 'Badminton'], 'address': {'city': 'Mumbai', 'state': 'Maharastra', 'country': 'India'}}

Encoding custom Python objects to JSON

Consider a user defined class called Person:

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

Let’s see what happens when we try to serialize an instance this class to JSON:

import json

p = Person('Rajeev', 24)
print(json.dumps(p))
# Output
TypeError: Object of type Person is not JSON serializable

Although, the json module can encode built-in python types like set, dict, list etc, It doesn’t understand how encode a user-defined class.

One way to work around this is to convert the object to a dict and then encode it:

import json

p = Person('Rajeev', 24)
print(json.dumps(p.__dict__))
{"name": "Rajeev", "age": 24}

Decoding JSON to custom Python type

The json.loads() method deserializes JSON to a Python type based on the following conversion table:

JSONPython
objectdict
arraylist
stringstr
number (int)int
number (real)float
trueTrue
falseFalse
nullNone

The json.loads() method allows you to provide an optional function called object_hook that is called with the result of any object literal decoded (a dict). The return value of object_hook is used instead of the dict.

We can use this function to decode a JSON string to a custom object. Let’s see an example where we decode a JSON string to a Person object that we defined in the previous section:

import json

def decode_person(dct):
  Person(dct['name'], dct['age'])

jsonData = '{"name": "Rajeev", "age": 24}'
p = json.loads(jsonData, object_hook=decode_person)

print(p.name) # Rajeev
print(p.age)  # 24

Note that, you can also pass a lambda function in the object_hook directly like so:

import json

jsonData = '{"name": "Rajeev", "age": 24}'
p = json.loads(jsonData, object_hook=lambda d: Person(d['name'], d['age']))

print(p.name) # Rajeev
print(p.age)  # 24