Login Register

Python JSON (JavaScript Object Notation)

What Is a JSON?

The JSON stands for “JavaScript Object Notation”, and especially a data format to store and share data between applications.

JSON data looks like a Python dictionary, but it is a text-based format that can be easily understood by humans and machines.

In Python programming, we use the json module to handle JSON data, and this module helps us convert Python objects (like dictionaries, lists) into JSON format.

  • Convert Python objects into JSON → called encoding
  • Convert JSON text back into Python objects → called decoding

This functionality helps us:

  • Sending data between a backend and a frontend
  • Storing user details in files
  • Communicating between APIs
  • Saving configuration settings

JSON is most popular because it is easy to read, works with multiple programming languages.

Why We Learn Python JSON?

  1. Data Exchange: JSON is used in APIs, web applications and databases for data communication.
  2. Simplicity: JSON syntax is easy to learn and resembles Python dictionaries.

Getting Started with Python JSON

Python does not directly read or write JSON, so it provides a special built-in module called json.

This json module come with multiple tools, such as:

  • Convert Python data → JSON text
  • Convert JSON text → Python data
  • Save JSON into files
  • Load JSON from files

You can consider json module as a translator that helps Python to talk with other systems using the JSON language.

How To Import json Module?

You can import it using the following command:

import json

Code Example of JSON:

import json

# A simple Python dictionary
profile = {
"username": "student_101",
"score": 85,
"active": True
}

# Convert Python dictionary to JSON string
json_text = json.dumps(profile)
print("Converted to JSON:", json_text)

Explanation of the code:

  • First, we imported the json module.
  • Then we created a small Python dictionary.
  • After we used the json.dumps() to changed the Python dictionary into JSON text.

Important JSON Methods in Python

When you work with JSON data so the json module gives you four important methods. These methods help you convert Python data to JSON and JSON back to Python, and also help you store JSON in files.

Now we understand each method with an example:

1) json.dumps() – Convert Python Object to JSON String

  • This method takes a Python object (like a dict, list, or tuple) and converts it into a JSON-formatted string.
  • We can use this method to send JSON data through APIs, print JSON, or store JSON in a database.

Example code:

import json

student = {
"name": "Rehan",
"marks": [78, 82, 91],
"active": True
}

json_string = json.dumps(student)
print("JSON Output:", json_string)

Output:

JSON Output: {"name": "Rehan", "marks": [78, 82, 91], "active": true}

2) json.dump() – Save JSON Data into a File

  • This method writes JSON data directly into a file.
  • Use it when you want to save data permanently on disk.

Example code:

import json

settings = {
"theme": "dark",
"notifications": False,
"volume": 65
}

with open("app_settings.json", "w") as file:
json.dump(settings, file)
  • This will create a file named app_settings.json with the converted JSON inside it.

3) json.loads() – Convert JSON String to Python Object

  • This method takes a JSON-formatted string and turns it into a Python object (dict, list, etc.).
  • It is helpful when we receive JSON data from an API or user input.

Example of json.loads():

import json

json_data = '{"city": "Ahmedabad", "temp": 31, "unit": "C"}'

python_obj = json.loads(json_data)
print("Converted:", python_obj)

Final output:

Converted: {'city': 'Ahmedabad', 'temp': 31, 'unit': 'C'}

4) json.load() – Read JSON Data from a File

  • This method reads JSON from a file and converts it to a Python object.
  • Use it when you want to load stored JSON data back into your program.

Example code:

import json

with open("app_settings.json", "r") as file:
settings_data = json.load(file)

print("Settings:", settings_data)

Advanced JSON Features In Python

Advanced features contain JSON formatting, handling complex data, and Customizing Serialization.

1. Formatting JSON Output

The json.dumps() method allows you to format JSON data for better readability using the indent parameter.

Example: Pretty-Printed JSON

import json

profile = {
"username": "coder101",
"active": True,
"score": 88
}

# Pretty JSON
pretty = json.dumps(profile, indent=4)
print("Clean JSON Output:\n", pretty)

Output:

Clean JSON Output:
{
"username": "coder101",
"active": true,
"score": 88
}

2. Handling Complex Data

Python can handle data structures like nested dictionaries and lists when converting to JSON form.

Example: Nested JSON

import json

student = {
"name": "Rohan",
"grades": [85, 90, 92],
"details": {
"college": "Tech Institute",
"year": 2025
}
}

nested_json = json.dumps(student, indent=4)
print("Nested JSON Data:\n", nested_json)

Output of this code:

Nested JSON Data:
{
"name": "Rohan",
"grades": [
85,
90,
92
],
"details": {
"college": "Tech Institute",
"year": 2025
}
}

3. Customizing Serialization

If you have non-standard Python objects, you can customize their JSON serialization using a helper function.

Example: Serializing Custom Objects

import json
from datetime import datetime

class Product:
def __init__(self, title, created_on):
self.title = title
self.created_on = created_on

# Custom converter for Product
def convert_product(item):
if isinstance(item, Product):
return {
"title": item.title,
"created_on": item.created_on.strftime("%d-%m-%Y")
}
raise TypeError("Object cannot be converted to JSON")

item = Product("Wireless Mouse", datetime(2024, 8, 19))

json_result = json.dumps(item, default=convert_product, indent=4)
print("Product JSON:\n", json_result)

Output of the program:

Product JSON:
{
"title": "Wireless Mouse",
"created_on": "19-08-2024"
}