Python Principles

How to use JSON in Python

JSON is a way to represent data such as lists, numbers, and strings as text.

This post explains how to encode, decode, and work with JSON in Python.

The JSON module

To work with JSON data, import the JSON module:

import json

This module has the loads and dumps functions that let you parse and encode data as JSON.

Converting to JSON

Use the json.dumps function to convert any data structure to JSON represented as a string:

>>> numbers = {1: "one", 2: "two"}
>>> json.dumps(numbers)
'{"1": "one", "2": "two"}'

The dumps means "dump as a string"

Converting from JSON

Use the json.loads function to load a Python data structure from a string of JSON data. For example:

>>> numbers = json.loads('{"1": "one", "2": "two"}')
>>> numbers["1"]

Why use JSON?

JSON is usually used to represent data in a textual format that's easy for programs to read. This might be necessary to transmit data between systems.

For example, many APIs use JSON to represent their data. Your Python script might request some data from another system -- this could, for example, be your script querying Facebook to find the number of times a page was liked. The server might then answer with data encoded in the JSON format, which you'd then use json.loads to load and work on.

How do I encode more complex things?

JSON only works for "simple" data types, such as strings, dictionaries, lists, etc. If you need to encode objects or custom types, you can use the Pickle Module. Note that unpickling untrusted data is a security risk, however.

Improve your Python skills fast

The fastest way to learn programming is with lots of practice. Learn a programming concept, then write code to test your understanding and make it stick. Try our online interactive Python course today—it's free!

Learn more about the course

Want to get better at Python quickly? Try our interactive lessons today! Memberships are 100% FREE this week only!