Working With JSON in Python

The implementation of JSON in Python is small and concise, and you can read its source code (written in Python) at Lib/json.

Although similar looking, Python Dictionaries and JSON are quite different. Dictionaries are high-level Python Objects, while JSON is pure text.  

We can go from one format to another using the four methods provided by the native JSON module in Python.

From JSON to Dictionaries

  • Use .loads() to deserialize  from a JSON string.
  • Use .load() to load a JSON file in memory.

Deserializing a JSON string, like an API response, to a Python Dictionary, with .loads().

import json
import requests

# Using the jsonplaceholder API to illustrate
api_json = requests.get('')

> str

> '{\n  "userId": 1,\n  "id": 1,\n  "title": "delectus aut autem",\n  "completed": false\n}'

json_to_dict = json.loads(api_json.text)
> {'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}

> dict

Loading a JSON file in memory while also converting it to Dictionaries:

import json

with open("data.json") as json_file:
    json_data = json.load(json_file)
> list

> dict

From Dictionaries to JSON

  • Use .dumps() to serialize to a JSON string.
  • Use .dump() to serialize to a JSON file or file-like object.

Serializing a dictionary to a JSON string with .dumps():

import json

user_dict = {'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}

to_json = json.dumps(user_dict)

> '{"userId": 1, "id": 1, "title": "delectus aut autem", "completed": false}'

> str

Serializing a dictionary to a JSON file with .dump():

import json

with open("user_data_file.json", "w") as user_data_file:
    json.dump(user_dict, user_data_file)

A file named user_data_file.json must have been created.