How to Use the JSON Module in Python – A Beginner's Guide (2024)

/ #Python
How to Use the JSON Module in Python – A Beginner's Guide (1)
Ashutosh Krishna
How to Use the JSON Module in Python – A Beginner's Guide (2)

JSON (JavaScript Object Notation) is a popular, lightweight data interchange standard. It represents data structures made up of key-value pairs that's quite straightforward and human-readable.

JSON has become the industry standard for data interchange between online services. And it's 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.

Python's Built-in JSON Module

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.

How to Store JSON Data in a File

When working with JSON data in Python, you'll often need 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 you can subsequently read and use as needed.

The json.dump() function

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 requestsimport json# Make the GET request to the horoscope APIresponse = 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 filewith 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 find out 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}

How to Retrieve Data from a JSON File

You'll often need to read data from a JSON file. For example, you may 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 your Python programs.

The json.load() function

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 filewith open("horoscope_data.json", "r") as file: data = json.load(file)# Access and process the retrieved JSON datadate = data["data"]["date"]horoscope_data = data["data"]["horoscope_data"]# Print the retrieved dataprint(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.

How to Format the JSON Output

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 filewith 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.dumps() function

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 filewith open("horoscope_data.json", "r") as file: data = json.load(file)# Format the dataformatted_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 you can see 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.

JSON Encoding Custom Objects

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 jsonclass Person: def __init__(self, name, age): self.name = name self.age = ageclass 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 objectperson = Person("Ashutosh Krishna", 23)# Encode the custom object using the custom encoderjson_str = json.dumps(person, cls=PersonEncoder)# Print the encoded JSON stringprint(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.

How to Create JSON from a Python Dictionary

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 dictionarydata = { "name": "Ashutosh Krishna", "age": 23, "email": "ashutosh@example.com"}# Convert dictionary to JSON stringjson_str = json.dumps(data)# Print the JSON stringprint(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"}

How to Create a Python Dictionary from JSON

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 stringjson_str = '{"name": "Ashutosh Krishna", "age": 23, "email": "ashutosh@example.com"}'# Convert JSON string to Python dictionarydata = json.loads(json_str)# Access the dictionary valuesprint(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 Krishna23ashutosh@example.com

Wrapping Up

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 how to use the JSON module.

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

How to Use the JSON Module in Python – A Beginner's Guide (3)
Ashutosh Krishna

Application Developer at Thoughtworks India

If you read this far, thank the author to show them you care.

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

ADVERTIsem*nT

How to Use the JSON Module in Python – A Beginner's Guide (2024)

FAQs

What is the use of JSON module in Python? ›

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.

How to work with a JSON file in Python? ›

Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which contains the value in key-value mapping within { }.

How to read JSON variable in Python? ›

To read JSON data, you can use the built-in json module (JSON Encoder and Decoder) in Python. The json module provides two methods, loads and load, that allow you to parse JSON strings and JSON files, respectively, to convert JSON into Python objects such as lists and dictionaries.

What 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.

What does JSON module do? ›

This module contains functions for working with JSON data. You can use it to process JSON that is embedded in other file formats. For example, you can query JSON that is stored as lines in a large text file by using json:parse-as-xml with the text:collection function.

How to write a JSON with Python? ›

JSON can also be written to a file using the json. dump() method. Without first converting the dictionary into a JSON object, the "dump" function of the JSON package simply writes the dictionary to a file in the JSON format.

How to format JSON data using Python? ›

After importing the json module, you can use .dumps() to convert a Python dictionary to a JSON-formatted string, which represents a JSON object. In the numbers_present dictionary, the keys 1 , 2 , and 3 are numbers. Once you use .dumps() , the dictionary keys become strings in the JSON-formatted string.

How do you send JSON data using Python? ›

Step 1: Create a folder containing the data you want to send. Step 2: Use the jsonify() function provided by Flask to convert the data to JSON format and send it as a response. Step 3: Test the application. If the application is working correctly, you should see the JSON data in the web browser.

How to convert JSON to data in Python? ›

Parse JSON - Convert from JSON to Python

If you have a JSON string, you can parse it by using the json.loads() method. The result will be a Python dictionary.

Why use JSON in Python? ›

JSON is a standardized format commonly used to transfer data. 00:33 There's no way to easily transfer native Python objects over the internet, and that's why we have JSON.

How to parse JSON in Python example? ›

To parse JSON string Python firstly we import the JSON module. We have a JSON string stored in a variable 'employee' and we convert this JSON string to a Python object using json. loads() method of JSON module in Python. After that, we print the name of an employee using the key 'name' .

How to install JSON module in Python? ›

Python comes with an in-built JSON library in version 3.5. This means there is no need to install any additional packages for the basic JSON functionality. However,if you're using the old version, i.e., the version below 3.5, you can opt for alternative JSON libraries like SimpleJSON.

What does Python JSON tool do? ›

Python supports the JSON format through the built-in module named json . The json module is specifically designed for reading and writing strings formatted as JSON. That means you can conveniently convert Python data types into JSON data and the other way around.

What is the purpose of JSON? ›

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 the use of JSON package? ›

It is used by the npm CLI (and yarn) to identify your project and understand how to handle the project's dependencies. It's the package. json file that enables npm to start your project, run scripts, install dependencies, publish to the NPM registry, and many other useful tasks.

Why is JSON library used? ›

JSON or JavaScript Object Notation is a lightweight format to exchange data. Compared to XML , JSON consumes less data and hence it is faster than XML. So JSON is better than XML because to parse XML you need a parser , but you can parse JSON using JavaScript. Not only that JSON is also simpler than XML .

Top Articles
Don't Fear The "Penalty"! - Financial 180
9 Habits That Will Get Your Credit Score Above 800
Star Wars Mongol Heleer
Ohio Houses With Land for Sale - 1,591 Properties
Room Background For Zepeto
Mrh Forum
Apex Rank Leaderboard
Coffman Memorial Union | U of M Bookstores
Practical Magic 123Movies
Directions To 401 East Chestnut Street Louisville Kentucky
Pj Ferry Schedule
Find The Eagle Hunter High To The East
What is a basic financial statement?
Craigslist Chautauqua Ny
Transformers Movie Wiki
South Bend Tribune Online
Munich residents spend the most online for food
Craigslist Free Stuff Greensboro Nc
Carolina Aguilar Facebook
Golden Abyss - Chapter 5 - Lunar_Angel
Full Standard Operating Guideline Manual | Springfield, MO
Why Should We Hire You? - Professional Answers for 2024
Uta Kinesiology Advising
Slim Thug’s Wealth and Wellness: A Journey Beyond Music
Wood Chipper Rental Menards
Rek Funerals
Netspend Ssi Deposit Dates For 2022 November
Gopher Hockey Forum
24 Hour Drive Thru Car Wash Near Me
100 Million Naira In Dollars
APUSH Unit 6 Practice DBQ Prompt Answers & Feedback | AP US History Class Notes | Fiveable
Storelink Afs
Murphy Funeral Home & Florist Inc. Obituaries
Appleton Post Crescent Today's Obituaries
Vip Lounge Odu
Ewwwww Gif
Daily Times-Advocate from Escondido, California
Blackwolf Run Pro Shop
Craigslist Pets Plattsburgh Ny
Www.craigslist.com Waco
2132815089
Myrtle Beach Craigs List
Vintage Stock Edmond Ok
Grizzly Expiration Date Chart 2023
Funkin' on the Heights
Greatpeople.me Login Schedule
Marcel Boom X
March 2023 Wincalendar
Appsanywhere Mst
7 National Titles Forum
Latest Posts
Article information

Author: Duncan Muller

Last Updated:

Views: 6042

Rating: 4.9 / 5 (59 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Duncan Muller

Birthday: 1997-01-13

Address: Apt. 505 914 Phillip Crossroad, O'Konborough, NV 62411

Phone: +8555305800947

Job: Construction Agent

Hobby: Shopping, Table tennis, Snowboarding, Rafting, Motor sports, Homebrewing, Taxidermy

Introduction: My name is Duncan Muller, I am a enchanting, good, gentle, modern, tasty, nice, elegant person who loves writing and wants to share my knowledge and understanding with you.