4 Great Python functions to handle JSON data super easily

Better Everything
6 min readJan 24, 2023

--

JSON is a format to structure data. It is widely used to store and send data. In this article I will show you how to use 4 Python functions to work with JSON. The functions are part of the built-in Python package: json.

The functions that we will discuss are:

  1. load, a function that can be used to transform a JSON file into a Python dictionary.
  2. loads, a function that can be used to transform a JSON string into a Python dictionary.
  3. dump, a function that can be used to transform a Python dictionary into a JSON file.
  4. dumps, a function that can be used to transform a Python dictionary into a JSON string.

Python dictionaries and JSON

As you might have noticed all functions work with Python dictionaries. That is because the Python datatype dictionary is very similar to JSON objects. First of all, both datatypes consist of key-value pairs. Each key-value pair has one key and one value. The key and value are separated by a colon-symbol (:) in both a dictionary and JSON. And both datatypes begin and end with curly brackets ({}).

But the similar structure is the most important, since this makes it easy to transform data from one datatype to another.

Using the json package in Python

Since the json package is built-in you don’t have to install it separately. All you have to do to make use of its functions is import the package. To import the json package in a script you only have to write one import statement. Import statements are typically put at the top of a Python script. The import statement for the json package is:

import json
The json package of Python makes it easy to work with JSON data in Python scripts.
The json package of Python makes it easy to work with JSON data in Python scripts. Image by catalyststuff on Freepik

An example JSON object

To show how the first two Python functions work, here is an example JSON object about a person named Jason.

{
"name": "Jason",
"age": 46,
"address": {
"street": "Castle Street",
"number": 1,
"city": "London"
},
"happy": true,
"languages": ["English", "Japanese"]
}

1 — load, a function that can be used to transform a JSON file into a Python dictionary

The load function is used when you have a JSON file that you want to work with in Python. Let’s imagine we have a JSON file called person1.json containing the JSON object above.

First we have to load the file itself into Python. This can be done with a with-open-as statement. Let’s look at an example:

import json

with open('person1.json') as f:

In the code above we specify the filepath of the file we want to open. In this case I placed the Python script in the same directory (folder) as the JSON file, so the filepath is just the filename. In the lines that will follow we can make use of the file object stored at variable f.

We will now pass the file object to the load function to transform it into a dictionary. Since the load function comes from the json package we write: json.load to call the function. The function will return the data as a dictionary and it will be assigned to variable data.

Here is the code example for transforming a JSON file into a Python dictionary:

import json

with open('person1.json') as f:
data = json.load(f)
print(data)

This will output a nice Python dictionary:

{'name': 'Jason', 'age': 46, 'address': {'street': 'Castle Street',
'number': 1, 'city': 'London'}, 'happy': True, 'languages':
['English', 'Japanese']}

2 — loads, a function that can be used to transform a JSON-formatted Python string into a Python dictionary

The loads function is used when you have a JSON-formatted Python string. In practice, JSON formatted strings can enter a Python script as part of an API response for example. So the data will already be in Python, but when it is transformed into a dictionary looking up data will get easier. For example, when you want to know if Jason is happy, you look up the key happy in the dictionary and you will find the value True. Looking up keys is not possible in strings, which is why we rather have a dictionary.

To see how the loads function works, we will make a JSON formatted string. It will contain the same data as in the example object above. The JSON string will be stored at variable person, which will be passed to the loads function. This function will return the data as a dictionary and it will be assigned to variable data, just like the load function. The only difference is that loads takes a string as an argument and load takes a file object.

Here is the code example for transforming a JSON-formatted string into a Python dictionary:

import json

person = """{
"name": "Jason",
"age": 46,
"address": {
"street": "Castle Street",
"number": 1,
"city": "London"
},
"happy": true,
"languages": ["English", "Japanese"]
}"""

data = json.loads(person)
print(data)

This script will output the same dictionary as the example of the load function.

3 — dump, a function that can be used to transform a Python dictionary into a JSON file

Now we will take a closer look at the dump function. You can use this function to make a JSON file. First you have to open a file and then you will pass the file object to the dump function. You also have to pass the dictionary that you want to save as JSON to the function.

Here is the code example for transforming a Python dictionary into a JSON file:

import json

person = {'name':"Jason",'age':46}

with open('test.json','w') as f:
json.dump(person,f)

In the above example we have the dictionary person. The data in that dictionary will be written into file test.json.

We first have to write a with-open-as statement to create a file object. Besides the desired filename, we also pass a string with value w to the open function. This will open the file in write mode, so that we can write data into it.

Then we call the dump function and pass the dictionary as the first argument and the file object f as the second argument. After running the example code, a file will be created called test.json. It will contain the same data as the dictionary in valid JSON format.

4 — dumps, a function that can be used to transform a Python dictionary into a JSON-formatted Python string.

Finally we will use the dumps function to make a JSON-formatted string from a dictionary. This one is really simple. All you have to do is pass a dictionary to the dumps function and it will return a JSON-formatted string.

Here is the code example for transforming a Python dictionary into a JSON-formatted string:

import json

person = {'name':"Jason",'age':46}

data = json.dumps(person)
print(data)

This outputs a nice JSON-formatted Python string. This can be used as a response for API requests for example.

{"name": "Jason", "age": 46}

Thank you for reading!

I hope you now have a better understanding of the 4 important Python functions to work with JSON data. load and loads to transform JSON files and strings into dictionaries. And dump and dumps to make JSON files and strings from dictionaries.

As a reminder the functions with names with an ‘s’ in them (loads and dumps) are the functions that work with strings (‘s’ for string).

To learn more about Python and programming follow this page and check out my E-books:

--

--

Better Everything

✅Programming, Data & Business ✅Automation & Optimization ✅Knowledge & Inspiration