10 Examples to Learn the JSON module of Python

Author:Murphy  |  View: 21747  |  Time: 2025-03-23 18:37:26

JSON, which stands for JavaScript Object Notation, is a very frequently used file (or data) format. Although it was derived from JavaScript, JSON is language-independent and most Programming languages have parsers available to work with JSON files.

JSON can be considered as a collection of key-value pairs, just like a dictionary in Python.

Here is a simple JSON file:

Python">{"name": "Jane", "age": 28, "city": "Houston"}

As we see in the example above, JSON is human-readable, you can naturally read JSON and understand what data it contains. It is also easy for machines to parse and generate.


Why is JSON so popular?

Numerous factors contribute to the prevalent use of JSON in software development and programming. Let's list some of them:

  1. Readability: As we can observe in the example above, JSON is easy to read and write, which makes it a great choice for storing data that you want to be human-readable.
  2. Lightweight: JSON is not very verbose, which makes it easy to transfer it over networks, and parsing and loading it quicker.
  3. Structure: It's a structured format to store data in a format that can be easily read by humans and machines.
  4. Interoperability: JSON is language-independent and can be used in any language, not just JavaScript. This makes it a great choice for data interchange between different programming languages.

You can become a Medium member to unlock full access to my writing, plus the rest of Medium. If you already are, don't forget to subscribe if you'd like to get an email whenever I publish a new article.


JSON with Python

The built-in json module of Python provides an easy and efficient way to work with JSON format. We will go over 10 examples to demonstrate the common tasks you can perform with this module.

Example 1: Converting Python object into JSON string

import json

data = {
    "name": "John Doe",
    "age": 28,
    "city": "Houston"
}

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

# output
{"name": "John Doe", "age": 28, "city": "Houston"}

The dumps method converts a dictionary to a string in json format. So the type of the variable json_data above is string.

type(json_data)

# output
str

Example 2: Pretty Printing JSON

import json

data = {
    "name": "John Doe",
    "age": 28,
    "city": "Houston"
}

json_data = json.dumps(data, indent=4)
print(json_data)

# output
{
    "name": "John Doe",
    "age": 28,
    "city": "Houston"
}

We can use the indent parameter to make the file more readable.


Example 3: Sorting the keys

import json

data = {
    "name": "John Doe",
    "age": 28,
    "city": "Houston"
}

json_data = json.dumps(data, sort_keys=True, indent=4)
print(json_data)

# output
{
    "age": 28,
    "city": "Houston",
    "name": "John Doe"
}

Remember a JSON file is a collection of key-value pairs. We can sort these pairs by keys using the sort_keys parameter.


Example 4: Loading JSON into Python object

import json

json_data = '{"name": "John Doe", "age": 28, "city": "Houston"}'
data = json.loads(json_data)

print(data)
print(data['name'])  # Accessing value of the 'name' key

# output
{'name': 'John Doe', 'age': 28, 'city': 'Houston'}
John Doe

Consider we have a JSON file stored as a string. We can convert it to a Python object of type dictionary using the loads function. Let's check the type of this file.

type(data)

# output
dict

Example 5: Writing JSON to a file

import json

data = {
    "name": "John Doe",
    "age": 28,
    "city": "Houston"
}

with open('data.json', 'w') as file:
    json.dump(data, file)

In this example, we have a Python dictionary called data . Then, we use the dump method to write its content to a JSON file named data.json , which looks like the following:

(image by author)

Example 6: Reading JSON from a file

import json

with open('data.json', 'r') as file:
    data = json.load(file)

print(data)

# output
{'name': 'John Doe', 'age': 28, 'city': 'Houston'}

We can use the load method to read the content of a JSON file into a Python dictionary.


Example 7: The default parameter

The default parameter of the dumps function can be used for serializing complex Python objects, which otherwise can't be serialized.

For instance, the following code raises a TypeError because of the datetime object:

import json

data = {
    "name": "John Doe",
    "age": 28,
    "city": "Houston",
    "birthday": datetime.datetime.now()
}

json_data = json.dumps(data, indent=4)

# output
TypeError: Object of type datetime is not JSON serializable

To handle this error, we can write a custom function that tells the dumps function how to serialize this object:

import json
import datetime

def datetime_serializer(x):
    if isinstance(x, datetime.datetime):
        return x.isoformat()

data = {
    "name": "John Doe",
    "age": 28,
    "city": "Houston",
    "birthday": datetime.datetime.now()
}

json_data = json.dumps(data, indent=4, default=datetime_serializer)
print(json_data)

# output
{
    "name": "John Doe",
    "age": 28,
    "city": "Houston",
    "birthday": "2023-05-14T07:22:53.917531"
}

Example 8: The default parameter with a custom class

Let's say we have a custom class called Person and want to convert an instance of it to JSON.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person = Person("John", 30)
json.dumps(person)  # Raises TypeError

# output
ypeError: Object of type Person is not JSON serializable

We can define a function to tell how to serialize a Person object:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

def person_to_dict(person):
    return {"name": person.name, "age": person.age}

person = Person("John", 30)
json.dumps(person, default=person_to_dict)

# output
'{"name": "John", "age": 30}'

Example 9: JSONEncoder

The JSONEncoder class gives us more control over the serialization process when converting a complex Python object into JSON. Instead of providing a default function to json.dumps(), we can create a subclass of JSONEncoder and override its default() method.

Let's do the same example with the Person class but using JSONEncoder instead of the default parameter.

import json

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

class PersonEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, Person):
            return {'name': o.name, 'age': o.age}
        return super().default(o)

person = Person("John", 30)
json.dumps(person, cls=PersonEncoder)

# output
'{"name": "John", "age": 30}'

The PersonEncoder is a subclass that inherits from JSONEncoder .


Example 10: The skipkeys parameter

The skipkeys parameter in dumps is used for specifying whether keys that are not of the basic types (str, int, float, bool, None) should be skipped instead of raising a TypeError. It comes in handy when working with large files.

Let's do an example with a tuple used as key:

import json

data = {
  (1, 2): "tuple_key",
  "normal_key": "value"
}

print(json.dumps(data))

# output
TypeError: keys must be str, int, float, bool or None, not tuple

As we see in the output, a TypeError is raised. If we set the value of the skipkeys parameter as True , the tuple key will be skipped without raising an error.

import json

data = {
  (1,2): "tuple_key",  # tuple as keys are not JSON-serializable
  "normal_key": "value"
}

print(json.dumps(data, skipkeys=True))

# output
{"normal_key": "value"}

Final words

We learned about the json module of Python, which is a powerful tool for working with JSON data. It provides functions and methods with a high degree of flexibility and control over the serialization and deserialization process.

The examples in this article covered topics like converting Python objects to JSON and vice versa, handling more complex data structures, and customizing the process to handle special cases.

Keep in mind that practice is essential in mastering any new concept and software tool so don't hesitate to experiment with these examples and try out different ones.

Thank you for reading. Please let me know if you have any feedback.

Tags: Artificial Intelligence Data Science Programming Python Python Programming

Comment