Read and write JSON files

JSON (Java Script Object Notation) is a data format that works a lot like dictionaries in Python.

Here’s a simple example of what JSON file data looks like. This JSON object contains two attributes, “name” and “age”:

{"name": "Rose", "age": 10}

If you paste that text into a new text file and make sure the file name ends with “.json” you will have a JSON data file.

You might notice that this could be copied and pasted into a Python file to create a dictionary. Here’s what that would look like in a Python program that creates the dictionary and prints the values:

person = {"name": "Rose", "age": 10}
print(person['name'])
print(person['age'])

Interestingly, this same exact code also works in the JavaScript language. (It’s called JavaScript object notation…) You can try it if you open your web browser’s developer tools and paste the commands into the console. Try it! (developer tools are often opened with F12 button, or control+shift+i)

If you have a dictionary in your Python program, it is pretty easy to save it as a JSON file. Here’s what that looks like if you start with the previous program and add some code to save the dictionary as a JSON file:

import json

person = {"name": "Rose", "age": 10}
json_file = open('person.json', 'w')
json.dump(person, json_file)
json_file.close()

Here we import json and then use theĀ json.dump() function to save the dictionary into a json file. A file object has to be created first using the open() function.

You can also easily load JSON data from a file using the json.load() function:

import json

f = open('person.json', 'r')
person = json.load(f)
f.close()

# now person is a Python dictionary:
print(person['name'])

To make the code work, you need to have created the person.json file in your working directory. You can try adding or changing the JSON data and then loading the file again – it will be updated with the new data from the file.

You can store lists and dictionaries inside your main dictionary object, which makes it possible to store large and complicated data structures in a single JSON file. Being able to save and load that type of data with only a few lines of code is very powerful.

Many websites have API’s (application programming interface) that let you request data from their website. For example, you could write a program that requests weather data from a site. Or you could request sports statistics, stock market prices, or many other types of data. In many cases, the website will send the data to you in JSON format, so this is a good reason to learn how to open JSON files.