In this tutorial, you’re going to learn how to convert a JSON file or string into a Python dictionary. Being able to work with JSON data is an important skill for a Python developer of any skill level. In most cases, data you access through web APIs will come in the form JSON data. Being able to convert these JSON objects into Python dictionaries will allow you to work with the data in meaningful ways.
By the of this tutorial, you’ll have learned:
- How to load a JSON file into a Python dictionary
- How to load a JSON string into a dictionary
- How to load data from an API into a Python dictionary
Table of Contents
What is JSON?
JSON stands for JavaScript Object Notation and it’s a popular format used to represent data. While originating from JavaScript, the format spread quickly due to its versatility. The format itself is quite similar to that of a Python dictionary. However, in many cases, the data comes in a string representing the object. We need to convert that string into a Python dictionary in order to work with it in Python.
Using JSON with Python
Python comes with a built-in library, json
, that lets you work with JSON objects in meaningful ways. In this tutorial, we’ll be looking at two of its functions that allow you to convert JSON objects to Python dictionaries:
json.load()
, which loads a JSON file into a Python dictionaryjson.loads()
, which loads a string representation of a JSON file into a Python dictionary
In the second function, as you may have guessed, the s
suffix refers to string
. In the following sections, you’ll learn how to use these functions to convert a JSON object into a Python dictionary.
Load a JSON File into a Python dictionary
In this section, you’ll learn how to use the json.load()
function to load a JSON file into a Python dictionary. If you want to follow along, you can download the file here. The file represents data from the internal space station, the API we’ll explore later on in the tutorial.
Let’s see how you can use the load()
function to load an external JSON file:
# Loading a JSON File to a Python Dictionary
import json
with open('/Users/nikpi/Desktop/iss-now.json', 'r') as file:
data = json.load(file)
print(data)
# Returns:
# {'message': 'success', 'iss_position': {'latitude': '41.8157', 'longitude': '-138.3051'}, 'timestamp': 1652700632}
Let’s break down what we did in the code above:
- We loaded the
json
library - We used a context manager to load our file in “read” mode using the alias
file
- We then used the
json.load()
function to load our file into a variable,data
- Finally, we printed our resulting dictionary
While you can do this without using a context manager, the context manager handles closing the file, thereby preserving memory.
We can verify the type of the resulting value by using the type()
function. This allows us to make sure that we actually loaded in a dictionary:
# Checking the Type of Our Loaded Dictionary
import json
with open('/Users/nikpi/Desktop/iss-now.json', 'r') as file:
data = json.load(file)
print(type(data))
# Returns:
# <class 'dict'>
In some cases, however, you won’t be working with data in a .json
file. In some cases, you’ll simply be presented with a string that represents the JSON object. In the following section, you’ll learn how to work with strings that represent JSON objects.
Load a JSON String into a Python Dictionary
In many cases, you’ll be given JSON data in a string format. Working with this is different than working with a .json
file. When working with string representations of a JSON file, you can use the json.loads()
function, which is used to “load a string”.
Let’s see how we can do this in Python using the json
module:
# Loading a JSON String into a Python Dictionary
import json
json_data = '''
{
"message": "success",
"iss_position": {
"latitude": "41.8157",
"longitude": "-138.3051"
},
"timestamp": 1652700632
}
'''
data = json.loads(json_data)
print(data)
# Returns:
# {'message': 'success', 'iss_position': {'latitude': '41.8157', 'longitude': '-138.3051'}, 'timestamp': 1652700632}
We can see from the example above that by passing in the string into the json.loads()
function, that we were able to easily transform a JSON string into a Pyhon dictionary. In the final section below, you’ll learn how to use the json.loads()
function to load a JSON response object from a web API into a Python dictionary.
Load JSON Data from an API into a Python Dictionary
In this section, you’ll learn how to use the json
and requests
libraries to get data from a web API and load it into a Python dictionary. For this, we’ll be using a NASA API that describes the current status of the International Space Station, which you can find here. The endpoint we’ll use the iss-now
endpoint, which provides the current location.
Let’s see how we can use the json
library to load the response we get back:
# Loading JSON Data from a Web API into a Python Dictionary
import json
import requests
url = 'http://api.open-notify.org/iss-now.json'
response = requests.get(url)
text = response.text
print(json.loads(text))
# Returns:
# {'message': 'success', 'iss_position': {'latitude': '-51.2011', 'longitude': '-74.2051'}, 'timestamp': 1652719740}
Let’s break down what we did here:
- We imported the required libraries,
json
andrequests
- We loaded the
response
variable using therequests.get()
function, passing in oururl
- We then got the text representation from the
response
object - Finally, we passed this into the
json.loads()
function to convert the string into a dictionary
This is quite a bit of code and thankfully there’s an easier way! The requests
library allows us to apply the .json()
method to the response object to convert it to a dictionary.
Let’s take a look at how this works:
# Convert an API JSON Response to a Python Dictionary
import requests
url = 'http://api.open-notify.org/iss-now.json'
response = requests.get(url)
data = response.json()
print(data)
# Returns:
# {'message': 'success', 'iss_position': {'latitude': '-45.0692', 'longitude': '-47.9368'}, 'timestamp': 1652720039}
In the example above, we didn’t need to import the json
library to convert the string into a Python dictionary. This works by loading a response
object using the .get()
function. We then apply the .json()
method to the response object to convert it to a Python dictionary.
Conclusion
In this tutorial, you learned how to convert JSON into a Python dictionary. You learned three different ways of accomplishing this: first by loading a .json
file into a Python dictionary, then by loading a JSON string into a dictionary, and, finally, working with web APIs.
Being able to work with JSON data is an important skill, given the ubiquity of the file format. Being able to convert this format to a Python dictionary will help you work with both web development and data science.
Additional Resources
To learn more about related topics, check out the tutorials below: