A Beginner’s Guide to the JSON Module in Python (2023)

A Beginner’s Guide to the JSON Module in Python (1)

Published in

Python in Plain English

·

9 min read

·

1 day ago

--

A Beginner’s Guide to the JSON Module in Python (3)

JSON (JavaScript Object Notation) is a popular, lightweight data interchange standard. It represents data structures made up of key-value pairs in a straightforward and human-readable manner. JSON has become the industry standard for data interchange between online services and is widely utilized in modern programming languages, including Python.

JSON data is frequently expressed as nested dictionaries, lists, and scalar values such as texts, numbers, booleans, and null. It is named JSON because it closely mimics the syntax used in JavaScript objects.

In this tutorial, you will explore the JSON module in Python and learn how to effectively work with JSON data.

JSON plays an important role in Python programming because it allows efficient data serialization and deserialization. It enables Python programs to effortlessly communicate with web services, exchange data, and store structured information.

Developers can use JSON to seamlessly link their Python programs with a variety of APIs, databases, and external systems that use JSON for data representation.

If you’re looking to learn how to interact with web services using Python, check out my tutorial on the requests module.

The built-in JSON module in Python provides a powerful set of methods and classes that make working with JSON data simple. Developers can use it to encode Python objects into JSON strings and decode JSON strings back into Python objects.

When working with JSON data in Python, it is frequently required to save the data or share it with others. Storing JSON data in a file enables quick retrieval and data persistence.

In this section, you’ll learn how to use Python’s json.dump() function to save JSON data to a file. This process involves serializing the JSON data and saving it to a file, which can subsequently be read and utilized as needed.

The json.dump() function in Python allows you to store JSON data directly into a file. This function takes two parameters: the data to be serialized and the file object where the data will be written.

To write JSON data to a file, you need to follow a few steps. First, you need to open a file in write mode, specifying the file path. Then, you can use the json.dump() function to serialize the data and write it to the file. Finally, you need to close the file to ensure that all the data is properly saved.

Let’s learn how to store data in a file using the horoscope API response as an example.

Assume you have made a GET request to the following URL: https://horoscope-app-api.vercel.app/api/v1/get-horoscope/daily?sign=capricorn&day=today, which provides the daily horoscope for the Capricorn sign.

import requests
import json

# Make the GET request to the horoscope API
response = requests.get("https://horoscope-app-api.vercel.app/api/v1/get-horoscope/daily?sign=capricorn&day=today")
data = response.json() # Convert the response to JSON

# Store the JSON data in a file
with open("horoscope_data.json", "w") as file:
json.dump(data, file)

print("Data stored successfully!")

In the code above, you use the requests library to make a GET request to the Horoscope API. You then extract the JSON data from the response using the .json() method. Finally, you open a file named horoscope_data.json in write mode using the with statement, and you use json.dump() to store the data in the file.

Check out this tutorial to learn how to know your horoscope using Python.

If you open the horoscope_data.json file, you'll see contents similar to below:

{
"data": {
"date": "Jun 3, 2023",
"horoscope_data": "The forecast today is stormy. You may have sensed that there was some tension clouding the conversation at home. Resentments were left unsaid and subtle power games were played without resolution. Today, Capricorn, it all becomes too unbearable for you. Regardless of the risks involved, you will take measures to clear things up."
},
"status": 200,
"success": true
}

It is often required to read data from a JSON file. For example, you can need to read configuration settings from a JSON file. Python’s JSON module provides the json.load() function, which allows you to read and deserialize JSON data from a file.

In this section, you will learn how to use the json.load() function to retrieve JSON data from a file and work with it in our Python programs.

The json.load() function accepts a file object as an argument and returns deserialized JSON data in the form of Python objects such as dictionaries, lists, strings, numbers, booleans, and null values.

To read JSON data from a file, you need to open the file in read mode, extract the data using the json.load() function, and store it in a variable for further processing. It's important to ensure that the file being read contains valid JSON data; otherwise, it may raise an exception.

Let’s see how you can retrieve the data from the previously created horoscope_data.json file:

import json

# Retrieve JSON data from the file
with open("horoscope_data.json", "r") as file:
data = json.load(file)

# Access and process the retrieved JSON data
date = data["data"]["date"]
horoscope_data = data["data"]["horoscope_data"]

# Print the retrieved data
print(f"Horoscope for date {date}: {horoscope_data}")

In the code above, you open the file horoscope_data.json in read mode using the with statement. You then use the json.load() function to deserialize the JSON data from the file into the data variable. Finally, you access specific fields of the JSON data (e.g., "date" and "horoscope_data") and process them as needed.

When you read data from a JSON file and print it, the output is displayed as a single line, which may not resemble the structured format of JSON.

import json

# Retrieve JSON data from the file
with open("horoscope_data.json", "r") as file:
data = json.load(file)

print(data)

Output:

{'data': {'date': 'Jun 3, 2023', 'horoscope_data': 'The forecast today is stormy. You may have sensed that there was some tension clouding the conversation at home. Resentments were left unsaid and subtle power games were played without resolution. Today, Capricorn, it all becomes too unbearable for you. Regardless of the risks involved, you will take measures to clear things up.'}, 'status': 200, 'success': True}

The JSON module provides you with a json.dumps() function to serialize Python objects into a JSON formatted string. It provides various options for customization, including formatting the output to make it more human-readable.

The json.dumps() function provides several options to customize the output. The most commonly used is the indent which allows you to specify the number of spaces used for indentation.

import json

# Retrieve JSON data from the file
with open("horoscope_data.json", "r") as file:
data = json.load(file)

# Format the data
formatted_data = json.dumps(data, indent=2)

print(formatted_data)

Output:

{
"data": {
"date": "Jun 3, 2023",
"horoscope_data": "The forecast today is stormy. You may have sensed that there was some tension clouding the conversation at home. Resentments were left unsaid and subtle power games were played without resolution. Today, Capricorn, it all becomes too unbearable for you. Regardless of the risks involved, you will take measures to clear things up."
},
"status": 200,
"success": true
}

As you can see, the JSON data is now formatted with proper indentation enhancing its readability. This technique can be applied to any JSON data, allowing you to present JSON output in a more organized and visually appealing way.

Python’s JSON module provides a convenient command-line tool called json.tool that allows you to format and pretty-print JSON data directly from the command line. It is a useful utility for quickly visualizing the structure and contents of JSON data in a more readable and organized format.

To use json.tool, you can execute the following command in your command-line interface:

python -m json.tool <input_file> <output_file>

where:

  • python -m json.tool invokes the json.tool module using the Python interpreter.
  • <input_file> represents the path to the JSON file you want to format.
  • <output_file> is an optional argument that specifies the file to which you want to save the formatted JSON output. If not provided, the formatted output will be displayed on the console.

Let’s say you have a horoscope_data.json file with the following contents:

{
"data": {
"date": "Jun 3, 2023",
"horoscope_data": "The forecast today is stormy. You may have sensed that there was some tension clouding the conversation at home. Resentments were left unsaid and subtle power games were played without resolution. Today, Capricorn, it all becomes too unbearable for you. Regardless of the risks involved, you will take measures to clear things up."
},
"status": 200,
"success": true
}

Notice that the above JSON file has an indentation of two spaces.

To pretty-print this JSON file using json.tool, you can execute the following command:

python -m json.tool horoscope_data.json

The output will be:

{
"data": {
"date": "Jun 3, 2023",
"horoscope_data": "The forecast today is stormy. You may have sensed that there was some tension clouding the conversation at home. Resentments were left unsaid and subtle power games were played without resolution. Today, Capricorn, it all becomes too unbearable for you. Regardless of the risks involved, you will take measures to clear things up."
},
"status": 200,
"success": true
}

As seen in the example, executing the json.tool module with the input file path formats the JSON data and displays the formatted output on the console.

You can also redirect the formatted output to an output file by specifying the output file name as the second argument:

python -m json.tool horoscope_data.json formatted_data.json

This command formats the JSON data from horoscope_data.json and saves the formatted output to formatted_data.json.

The JSON module in Python allows you to encode and decode custom objects by using JSON encoder and decoder classes. You can define custom serialization and deserialization logic for your objects using these classes.

JSONEncoder class allows you to customize the encoding process. To define how your custom object should be encoded into JSON format, you can extend the JSONEncoder and change its default method.

Here’s an example of how you can extend the JSONEncoder class and customize the encoding process for a custom object:

import json

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

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

# Create a custom object
person = Person("Ashutosh Krishna", 23)

# Encode the custom object using the custom encoder
json_str = json.dumps(person, cls=PersonEncoder)

# Print the encoded JSON string
print(json_str)

In this example, you define a custom class Person with name and age attributes. You then create a subclass of JSONEncoder called PersonEncoder and override its default method. Within the default method, you check if the object being encoded is an instance of Person. If it is, you provide a JSON-serializable representation of the object by returning a dictionary containing the name and age attributes. If the object is not of type Person, you call the default method of the superclass to handle other types.

By using json.dumps and specifying the cls parameter as your custom encoder class PersonEncoder, you can encode the person object into a JSON string. The output will be:

{"name": "Ashutosh Krishna", "age": 23}

Similarly, you can specify custom decoding logic in the JSON decoder class, JSONDecoder. To define how JSON data should be decoded into your custom object, extend the JSONDecoder and override its object_hook function.

You can use the json.dumps() function provided by the JSON module to create JSON from a Python dictionary. This function takes a Python object, typically a dictionary, and converts it into a JSON string representation.

import json

# Python dictionary
data = {
"name": "Ashutosh Krishna",
"age": 23,
"email": "ashutosh@example.com"
}

# Convert dictionary to JSON string
json_str = json.dumps(data)

# Print the JSON string
print(json_str)

In this example, you have a Python dictionary data representing some data. By calling json.dumps(data), you convert the dictionary into a JSON string. The output will be:

{"name": "Ashutosh Krishna", "age": 23, "email": "ashutosh@example.com"}

To create a Python dictionary from JSON data, you can use the json.loads() function provided by the JSON module. This function takes a JSON string and converts it into a corresponding Python object, typically a dictionary.

import json

# JSON string
json_str = '{"name": "Ashutosh Krishna", "age": 23, "email": "ashutosh@example.com"}'

# Convert JSON string to Python dictionary
data = json.loads(json_str)

# Access the dictionary values
print(data["name"])
print(data["age"])
print(data["email"])

In this example, you have a JSON string json_str representing some data. By calling json.loads(json_str), you convert the JSON string into a Python dictionary. You can then access the values in the dictionary using their respective keys.

The output will be:

Ashutosh Krishna
23
ashutosh@example.com

Understanding the Python JSON module is necessary for working with JSON data because it is widely used for data exchange and storage in a variety of applications. You can efficiently handle JSON data, interface with APIs, and deal with configuration files if you learn the JSON module.

Originally published at https://blog.ashutoshkrris.in.

More content at PlainEnglish.io.

Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.

FAQs

What is the JSON module in Python? ›

JSON stands for JavaScript Object Notation and is a lightweight format for storing and transporting data. JSON is often used when data is sent from a server to a web page. Python has the built-in module json , which allow us to work with JSON data.

How to use Python to read a JSON file? ›

Reading From JSON

It's pretty easy to load a JSON object in Python. Python has a built-in package called json, which can be used to work with JSON data. It's done by using the JSON module, which provides us with a lot of methods which among loads() and load() methods are gonna help us to read the JSON file.

How to read objects from JSON in Python? ›

To parse a JSON data string to a Python object, use the json. loads() method of the built-in package named json. The json. loads() method parses the provided JSON data string and returns a Python dictionary containing all the data from the JSON.

Which is the best JSON module for Python? ›

orjson is a fast, correct JSON library for Python. It benchmarks as the fastest Python library for JSON and is more correct than the standard json library or other third-party libraries. It serializes dataclass, datetime, numpy, and UUID instances natively.

How to convert a string to JSON in Python? ›

Use the json.loads() function

you can turn it into JSON in Python using the json.loads() function. The json.loads() function accepts as input a valid string and converts it to a Python dictionary. This process is called deserialization – the act of converting a string to an object.

Why use JSON in Python? ›

Java Script Object Notation (JSON) is a light weight data format with many similarities to python dictionaries. JSON objects are useful because browsers can quickly parse them, which is ideal for transporting data between a client and a server.

How to write objects to JSON file in Python? ›

To dump a Python object to JSON string, you can use the json. dumps() method of the built-in json module. The json. dump() paired method (without the "s") converts the Python object to JSON string and writes it to a file.

How to put data into JSON format Python? ›

If you have a Python object, you can convert it into a JSON string by using the json. dumps() method.

How do you fetch data from a JSON file? ›

To fetch JSON from the server using the Fetch API, you need to use the JavaScript fetch() method and then call the response. json() method to get the JSON data as a JavaScript object. The response. json() method reads the data returned by the server and returns a Promise that resolves with a JSON object.

How to write data in JSON? ›

First, to write data to a JSON file, we must create a JSON string of the data with JSON. stringify . This returns a JSON string representation of a JavaScript object, which can be written to a file.

How to read a JSON file line by line in Python? ›

To Load and parse a JSON file with multiple JSON objects we need to follow below steps:
  1. Create an empty list called jsonList.
  2. Read the file line by line because each line contains valid JSON. ...
  3. Convert each JSON object into Python dict using a json. ...
  4. Save this dictionary into a list called result jsonList.
May 14, 2021

How to parse JSON and get value in Python? ›

Python has a built in module that allows you to work with JSON data. At the top of your file, you will need to import the json module. If you need to parse a JSON string that returns a dictionary, then you can use the json. loads() method.

How to check JSON data type in Python? ›

Follow the below steps:
  1. First, install jsonschema using pip command. pip install jsonschema.
  2. Define Schema: Describe what kind of JSON you expect.
  3. Convert JSON to Python Object using json. load or json. ...
  4. Pass resultant JSON to validate() method of a jsonschema .
May 14, 2021

Does Python have a JSON library? ›

Python Supports JSON Natively! Python comes with a built-in package called json for encoding and decoding JSON data.

What is the JSON library commonly used for? ›

JavaScript Object Notation (JSON) is a standardized format commonly used to transfer data as text that can be sent over a network. It's used by lots of APIs and Databases, and it's easy for both humans and machines to read.

Which two Python data types can relate to JSON? ›

You can convert Python objects of the following types, into JSON strings:
  • dict.
  • list.
  • tuple.
  • string.
  • int.
  • float.
  • True.
  • False.

How to convert CSV file to JSON in Python? ›

Convert CSV to JSON with Python
  1. import csv and import json packages.
  2. Create a file path to your CSV file: csvFilePath = 'csv_file_name.csv'
  3. Create a file path to your JSON file: jsonFilePath = 'json_file_name.json'
  4. Create an empty dictionary to store your converted JSON data: data = {}
  5. Open and read the CSV:

When should we use JSON? ›

JSON is used in electronic data exchange, such as transmitting data in web applications. Websites are made of web pages. These web pages display pre-stored information in a server and interact with the server using data formats such as JSON.

How to convert JSON object to text in Python? ›

Steps to Convert JSON String to TEXT File using Python
  1. Step 1: Prepare the JSON string. Let's review a simple example, where we'll create a JSON string based on the data below: ...
  2. Step 2: Create the JSON file. ...
  3. Step 3: Install the Pandas Package. ...
  4. Step 4: Convert the JSON String to TEXT using Python.

How to convert a string into JSON? ›

Convert String to JSON Using eval()

The eval() function in JavaScript is used to take an expression and return the string. As a result, it can be used to convert the string into JSON.

What does a JSON array look like? ›

A JSON array contains zero, one, or more ordered elements, separated by a comma. The JSON array is surrounded by square brackets [ ] . A JSON array is zero terminated, the first index of the array is zero (0). Therefore, the last index of the array is length - 1.

Which tool extract data from JSON? ›

Testsigma's free online Extract Text from JSON tool can extract text from an JSON document. It removes all special characters, leaving only textual content between tags. This is a good tool for extracting simple details from an JSON document.

How to fetch an object from an object in JSON? ›

getJsonObject() Method

It is used to get the (JsonObject)get(name). The method parses an argument name of type String whose related value is to be returned. It returns the object of the associated mapping for the parse's parameter. It returns null if the object has no mapping for the parameter.

Is it difficult to learn JSON? ›

JSON is not particularly hard to use because there aren't many prerequisites to using it. It's human-readable which makes it fairly accessible to even novice developers. JSON also has relatively few data types you need to know before you're able to use it, so it can be relatively easy to get started using JSON.

What is JSON format with example? ›

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).

What is a JSON object example? ›

JSON Object Example

A JSON object contains data in the form of key/value pair. The keys are strings and the values are the JSON types. Keys and values are separated by colon. Each entry (key/value pair) is separated by comma.

How do I manually write JSON? ›

How to Create JSON File?
  1. Using Text Editor. Open a Text editor like Notepad, Visual Studio Code, Sublime, or your favorite one. ...
  2. Using Online Tool. Open a JSON Formatter tool from the link below. ...
  3. Create a file from the JSON URL. The developer needs to work with API; nowadays, 95% of API returns data as JSON.
Jun 21, 2020

How to print JSON file in Python? ›

Python Pretty Print JSON
  1. Python Pretty Print JSON String. import json json_data = '[{"ID":10,"Name":"Pankaj","Role":"CEO"},' \ '{"ID":20,"Name":"David Lee","Role":"Editor"}]' json_object = json.loads(json_data) json_formatted_str = json.dumps(json_object, indent=2) print(json_formatted_str) ...
  2. Python Pretty Print JSON File.
Aug 3, 2022

Does JSON module come with Python? ›

Python comes with a built-in package called json for encoding and decoding JSON data.

What is JSON and why it is used? ›

It is a text-based way of representing JavaScript object literals, arrays, and scalar data. JSON is relatively easy to read and write, while also easy for software to parse and generate. It is often used for serializing structured data and exchanging it over a network, typically between a server and web applications.

What does Python JSON tool do? ›

In Python, the json module provides an API similar to convert in-memory Python objects to a serialized representation known as JavaScript Object Notation (JSON) and vice-a-versa.

What does package JSON type module do? ›

A package.json "type" value of "module" tells Node.js to interpret .js files within that package as using ES module syntax. The "type" field applies not only to initial entry points ( node my-app.js ) but also to files referenced by import statements and import() expressions.

References

Top Articles
Latest Posts
Article information

Author: Saturnina Altenwerth DVM

Last Updated: 19/08/2023

Views: 6378

Rating: 4.3 / 5 (64 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Saturnina Altenwerth DVM

Birthday: 1992-08-21

Address: Apt. 237 662 Haag Mills, East Verenaport, MO 57071-5493

Phone: +331850833384

Job: District Real-Estate Architect

Hobby: Skateboarding, Taxidermy, Air sports, Painting, Knife making, Letterboxing, Inline skating

Introduction: My name is Saturnina Altenwerth DVM, I am a witty, perfect, combative, beautiful, determined, fancy, determined person who loves writing and wants to share my knowledge and understanding with you.