JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. It’s extensively used in web applications for data transmission.

There is more to it than this one function. The Python Data I/O Mega Pack covers reading and writing files, csv, json, Excel and working with a database.

SQL is the language you use to ask a database questions. If you want to get better at it, SQLCrab runs real queries in the browser, nothing to install.

JSON is the format web APIs speak. It is a text format, so you can read it, write it and look at it in the browser without special tools.

Python has a json module in the standard library, so there is nothing to install.

With Python’s built-in json module, encoding and decoding JSON becomes a straightforward task. This means converting Python objects into JSON formatted strings and converting JSON strings back into Python objects.

Encoding Python Objects to JSON (json.dumps)

Let’s look at a practical example. Imagine you have a Python class called Student, and you’d like to serialize an instance of this class into JSON format.

Below, we instantiate a Student object and then use the json.dumps() method to transform this Python object into a JSON string.

import json

class Student:
def __init__(self, id, name, password):
self.id = id
self.name = name
self.password = password

pythonObj = Student(1,'ashley','123456')

# Serialize Python object to JSON formatted string
jsonObj = json.dumps(pythonObj.__dict__)
print(jsonObj)

As seen above, the result is a JSON-formatted string that represents the Student object:

{"password": "123456", "id": 1, "name": "ashley"}

Decoding JSON to Python Objects (json.loads)

The reverse process, decoding, converts a JSON string into a Python dictionary or object. This is performed using the json.loads() method.

Here’s how you can convert the earlier JSON string into a Python dictionary:

import json

j = json.loads('{"password": "123456", "id": 1, "name": "ashley"}')
print(j["name"])

For a more advanced use-case, you might want to decode the JSON string directly into a Python object. To achieve this, first define the Python class and then instantiate it using the parsed JSON data:

import json

class Student:
def __init__(self, id, name, password):
self.id = id
self.name = name
self.password = password

j = json.loads('{"password": "123456", "id": 1, "name": "ashley"}')
pythonObj = Student(**j)

print(pythonObj.id)
print(pythonObj.name)
print(pythonObj.password)

Understanding JSON encoding and decoding in Python is crucial for any developer working on data transmission or web application tasks. Python’s native support for JSON makes these operations intuitive and efficient.

The four functions you need

  • json.loads(text) turns a JSON string into a Python object.
  • json.dumps(obj) turns a Python object into a JSON string.
  • json.load(file) reads a file and parses it in one go.
  • json.dump(obj, file) writes an object to a file in one go.

The types line up almost one to one. A JSON object becomes a dict, an array becomes a list, a string stays a string, true becomes True and null becomes None.

Two things trip people up. A JSON number becomes an int or a float, never a string, so check the type before you compare it. And a dict key is always a string in JSON, even when it looks like a number.

Use indent=4 in dumps() when you want readable output while you are debugging. And use ensure_ascii=False if your text has other languages in it.

If you want to try this yourself, the exercises on PyChallenge turn the same idea into a few short problems with instant feedback.