Want to keep learning?

This content is taken from the Raspberry Pi Foundation & National Centre for Computing Education's online course, Programming 103: Saving and Structuring Data. Join the course to learn more.

Skip to 0 minutes and 3 seconds JavaScript Object Notation, or JSON, is a lightweight data interchange format that is easy for humans to read and write while remaining easy for machines to parse and generate. JSON is regularly used to when working with application programming interfaces, or APIs, such as those provided by Twitter, Facebook, and NASA. And it provides a standard format for those services to provide data to your programs. JSON is remarkably similar to Python’s dictionary data type in that it uses a key value paring to store data. Time to have a go at creating a project using a JSON structure to store the details of the first person on the moon, Neil Armstrong.

Skip to 0 minutes and 54 seconds So in this code, we start by importing the JSON library, which enables you to use JSON with Python. It then creates a dictionary called data storing three values. Name, which is the first key. And the value it references is the name of astronaut Neil Armstrong stored as a string. Then, the next key is age. And the value stored here is Neil’s age at the time of his death stored as an integer. And the last key is hobbies. And the value for this is a list formed of his hobbies.

Skip to 1 minute and 37 seconds It’s stored as a string To create persistent data storage of this information, use the standard file open method which creates a new writeable file, neil.json and the json.dump function which writes the dictionary to that file in JSON format. Now, round the code and open neil.json using a text editor. The contents should look like this. You can notice the name as the key and the value next to it, the age has a key and the value next to it, and the hobbies has a key and a list of values next to it. Now, try importing the JSON data back into the program using this code.

Skip to 2 minutes and 31 seconds This opens the JSON file in read, so r mode, and uses that JSON.load method to read to the JSON file. As you can see, that data2 is also a dictionary the same as data. So if we run this code, we will see that the data comes up as a dictionary with pairs of values and keys. Name has a key and the value next to it, age has a key and the value next to it, hobbies has a key and a list of values next to it. You can obtain the values from this dictionary by using the relevant keys as you learned about earlier this week.

Skip to 3 minutes and 14 seconds Now you may have noticed that I’ve chosen three different data types to be stored in the JSON file and a dictionary. JSON is much more flexible than CSV since you can store many different data types. I can mix integers, strings, lists, and even store another dictionary. Even with this complexity, JSON still provides an easy to read and write syntax that can be used to store complex data. JSON isn’t just a format for storing data. It can also be used to transmit data and is commonly used with APIs on the internet. For example, NASA provides an API that can be used to extract scientific and astronomical data and images taken during various missions.

Skip to 4 minutes and 4 seconds NASA offers this data in JSON format for free via public API and you can work with that data using Python. To work with data from the internet, you can use the request library which allows you to send and receive data over a network connection. In this example, the code uses their request library to get the data from NASA API and store it into an object r. The data in r is then parsed from JSON data into Python dictionary using r.JSON over here. And I’m going to run it. You can see we have a print statement underneath and we are going to see the data in repo. The entire dictionary structure is then printed to the repo.

Skip to 4 minutes and 59 seconds In the structure of this dictionary, there are many keys, one of which is explanation. So you can look at copyright is one key and the value associated with it, date is another key and a value associated next to it, and explanation is another key. The associated value provides a text description of an astronomical image. JSON is an amazing tool for structuring data, and over the next few steps, you will use it to make a game with persistence structured storage. Can you think of a project where it would be useful to store another dictionary inside a JSON file? Explain why in the comments section.

An introduction to JSON

JavaScript Object Notation or JSON is much more than a structured method to store data. JSON is the language that helps projects interact over the internet.

JSON is a lightweight data interchange format that is easy for humans to read and write while remaining easy for machines to parse and generate. JSON is regularly used when working with application programming interfaces (APIs) such as those provided by Twitter, Facebook, and NASA, as it provides a standard format for those services to provide data to your programs.

Tip: Parsing is where data is split into its component parts for checking or other processing.

Creating a JSON data structure

JSON is remarkably similar to Python’s dictionary data type, in that it uses a key–value pairing to store data. To demonstrate this you will create a project that will store the details of the first person on the moon, Neil Armstrong, using a JSON structure.

    import json
    data = {
        "Name": "Neil Armstrong",
        "Age": 82,
        "Hobbies": ["Aircraft design", "Fishing", "Astronaut"]
    }

This program first imports the json library, enabling us to use JSON with Python. It then creates a dictionary called data storing three values. The first key is Name and the value it references is the name of astronaut Neil Armstrong, stored as a string. The next key is Age and the value stored here is Neil’s age at the time of his death, stored as an integer. The last key is Hobbies and the value for this is a list of his hobbies, each stored as a string.

    with open("neil.json", "w") as f:
        json.dump(data, f)

To create persistent data storage of this information you use the standard file open method, which will create a new writable file, neil.json, and the json.dump function, which will write the dictionary to that file in JSON format.

Run the code yourself, and then open neil.json using a text editor.The contents should look like this:

    {"Name": "Neil Armstrong", "Age": 82, "Hobbies": ["Aircraft design", "Fishing", "Astronaut"]}

Notice that the JSON syntax is identical to Python’s dictionary.

Try importing the JSON data back into the program using the following code:

    with open("neil.json", "r") as f:
        data2 = json.load(f)
    print(data2)

This opens the JSON file in read "r" mode, and uses the json.load method to read the JSON file.

You should see that data2 is a dictionary, the same as data. You can obtain the values from this dictionary by using the relevant keys, as you saw earlier this week.

You may have noticed that I have chosen three different data types to be stored in the JSON file and dictionary. JSON is much more flexible than CSV in that you can store many different data types, mixing integers, strings, and lists, and can even store another dictionary. Even with this complexity, JSON still provides an easy to read and write syntax that can be used to store complex data.

Using JSON with a public API

Image of web browser open to the NASA API example URL

JSON is not just a format for storing data but one for transmitting data. As mentioned earlier, JSON is commonly used with APIs on the internet.

An example: Using the NASA API

NASA provides an API that can be used to extract scientific and astronomical data and images taken during various missions. NASA offers this data in JSON format for free via a public API and you can work with that data using Python. To work with data from the internet you can use the requests library, which allows you to send and receive data over a network connection.

import requests
r = requests.get("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY")
NASA = r.json()
print(NASA)

This example uses the requests library to get data from the NASA API and store it into an object r. The data in r is then parsed from JSON data into a Python dictionary using r.json(). The entire dictionary structure is then printed to the REPL. In the structure of this dictionary you would see many keys, one of which is explanation — the associated value provides a text description of an astronomical image.

Note: Depending on your setup you may need to install the Python package requests to try this example. The Installing Python packages guide provides advice on how to install Python packages for the most typical scenarios.

JSON is an amazing tool for structuring data. Over the next few steps you will see how to use it to make a game with persistent structured storage.

Can you think of a project where it would be useful to store another dictionary inside a JSON file? Explain why in the comments section.

Share this video:

This video is from the free online course:

Programming 103: Saving and Structuring Data

Raspberry Pi Foundation