This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 6: JSON files

Loading a JSON file

face Josiah Wang

The json module allows you to easily load a JSON file into its equivalent Python object (usually a dict or list).

To load your data from a JSON file, use json.load(file_object).

The following code loads the content from a file called input.json into a Python object named data. You can then manipulate data as you would a list or dict (depending on what is in input.json)

import json

with open("input.json", "r") as jsonfile: 
    data = json.load(jsonfile)

print(type(data))

To load your object directly from a JSON string rather than a file, use json.loads(string) (loads is short for ‘load string’).

import json

json_string = '[{"id": 2, "name": "Basilisk"}, {"id": 6, "name": "Nagaraja"}]'
data = json.loads(json_string)

print(data[0])  # {'id': 2, 'name': 'Basilisk'}
print(data[1]["name"]) # Nagaraja

The fancy term to describe this process is called deserialisation (converting a string to a data object).