Python

The Ultimate Guide to Handling JSON with Python

The Ultimate Guide to Handling JSON with Python
In: Python, NetDevOps

Did you hear about the Python developer who got lost in a JSON file? It took him hours to find the right key, only to realize it was a 'string' attached 🙂

Do you want to be able to read and write JSON files without breaking a sweat? Look no further! In this blog post, we'll be diving into the wonderful world of working with JSON in Python.

The built-in json module in Python provides us with powerful tools to easily convert dictionaries to JSON and vice versa, read and write data from and to JSON files, and even format our JSON data with indentation. We'll be exploring all of these functionalities in this post.

Converting Dictionary to JSON and Vice Versa

A dictionary is a collection of key-value pairs in Python. The json module in Python provides methods to convert a dictionary to JSON and vice versa. The json.dumps() method converts a Python dictionary to a JSON formatted string, while the json.loads() method converts a JSON formatted string to a Python dictionary.

It's understandable to get confused between json.dumps() and json.loads() as they sound quite similar. However, there's a simple trick to easily remember which one is used for what.

Think of dumps as dumping data out of Python, and loads as loading data into Python. json.dumps() is used to dump a Python object, such as a dictionary, into a JSON string. On the other hand, json.loads() is used to load a JSON string into a Python object, such as a dictionary.

So, the s in dumps stands for "string" and the s in loads stands for "string" as well, indicating that one is used for converting to a string, and the other is used for converting from a string.

With this simple mnemonic, you'll never get confused between json.dumps() and json.loads() again!

Converting a dictionary to JSON

The function takes a Python object, such as a dictionary or a list, and returns a string in JSON format that can be written to a file or print it.

import json

person = {"name": "Max", "age": 25, "city": "London"} #python dictionary
person_json = json.dumps(person)

print(person_json)
#output

{"name": "Max", "age": 25, "city": "London"}

Converting a JSON-formatted string to a dictionary

The function takes a JSON formatted string as an argument and returns a Python object such as a dictionary, list, string, integer, or boolean depending on the content of the JSON string.

import json

person_json = '{"name": "Max", "age": 25, "city": "London"}' #json formatted string
person = json.loads(person_json)

print(person)
print(type(person))
#output

{'name': 'Max', 'age': 25, 'city': 'London'}
<class 'dict'>

Reading from a JSON File

Python also provides a way to read data from a JSON file. The json.load() method is used to read data from a JSON file and convert it into a Python dictionary.

Let's assume the contents of the file looks like the following.

{
    "name": "Max",
    "age": 25,
    "city": "London"
}
import json

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

print(data)
#output

{'name': 'Max', 'age': 25, 'city': 'London'}

Writing to a JSON File

Python also provides a way to write data to a JSON file. The json.dump() method is used to write a Python dictionary to a JSON file.

import json

person = {"name": "Max", "age": 25, "city": "London"}

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

If you open the newly created JSON file, the contents will look like the following.

#person.json

{"name": "Max", "age": 25, "city": "London"}

You might have noticed that the JSON file we just created doesn't have an indentation. That's the topic we are going to discuss next.

Indentation Example

JSON data can be formatted with indentation to make it more readable. The json.dumps() and json.dump() method provides an optional parameter called indent that specifies the number of spaces to use for indentation.

To make the previous example more readable, let's use an indentation.

import json

person = {"name": "Max", "age": 25, "city": "London"}

with open('person.json', 'w') as f:
    json.dump(person, f, indent=4)
#person.json

{
    "name": "Max",
    "age": 25,
    "city": "London"
}

As you can see above, the content of the JSON file is more readable.

You can also use indentation with json.dumps() as shown below

import json

person = {"name": "Max", "age": 25, "city": "London"}
person_json = json.dumps(person, indent=4)

print(person_json)
#output

{
    "name": "Max",
    "age": 25,
    "city": "London"
}

How to Read JSON Data from a File and Format it with Indentation in Python?

Please note that indentation is not applicable with json.load() or json.loads() methods as they are used for reading data from a JSON file or a JSON formatted string, respectively, and converting it into a Python object.

The indent parameter is only applicable with the json.dump() and json.dumps() methods, as they are used for writing a Python object to a JSON file or a JSON formatted string, respectively, and formatting the JSON data with indentation.

So, if you want to format your JSON data with indentation while reading from a JSON file or a JSON formatted string, you need to read the data first using json.load() or json.loads(), and then use json.dumps() with the indent parameter to format the data with indentation.

Suppose you have a JSON file without any formatting as shown below, what you can do is use json.load() json.loads() and then use json.dumps()to add indentation.

#person.json

{"name": "Max", "age": 25, "city": "London"}
import json

# Read data from JSON file
with open('person.json') as f:
    data = json.load(f)

# Format data with indentation
formatted_data = json.dumps(data, indent=4)

# Print formatted data
print(formatted_data)
#output

{
    "name": "Max",
    "age": 25,
    "city": "London"
}

You can also indent it with a single line of code by combining both functions.

import json

data = '{"name": "Max", "age": 25, "city": "London"}'

# Convert the JSON string into an indented JSON string in one line
indented = json.dumps(json.loads(data), indent=4)

# Print the indented string
print(indented)

Closing Up

In summary, json.dumps() is used to convert a Python object into a JSON formatted string, while json.loads() is used to convert a JSON-formatted string into a Python object. On the other hand, json.dump() is used to write a Python object to a JSON file, while json.load() is used to read data from a JSON file and convert it into a Python object.

Table of Contents
Written by
Suresh Vina
Tech enthusiast sharing Networking, Cloud & Automation insights. Join me in a welcoming space to learn & grow with simplicity and practicality.
Comments
More from Packetswitch
Great! You’ve successfully signed up.
Welcome back! You've successfully signed in.
You've successfully subscribed to Packetswitch.
Your link has expired.
Success! Check your email for magic link to sign-in.
Success! Your billing info has been updated.
Your billing was not updated.