Python JSON Tutorial - Parse, Read, Write & Handle JSON

Introduction to JSON in Python

JSON, short for JavaScript Object Notation, is a lightweight format for storing and transporting data. In Python, it plays a pivotal role when working with APIs, configuration files, or structured data exchange. The good news? Python makes JSON handling intuitive through its built-in json module.

What Is JSON?

JSON is a string-based format that represents data as key-value pairs. It's similar to Python dictionaries, which makes it easier for developers to interact with.

Why Use JSON in Python?

  • Interchange data between frontend and backend (especially via APIs)
  • Save application settings or configurations
  • Serialize Python objects for storage or transmission

Importing the JSON Module

Start by importing Python's built-in module:

import json

Converting Python Objects to JSON (Serialization)

Serialization means converting a Python object (like a dict) into a JSON string using json.dumps().

import json

data = {"name": "Alice", "age": 30, "is_admin": False}
json_string = json.dumps(data)
print(json_string)
{"name": "Alice", "age": 30, "is_admin": false}

Explanation

json.dumps() converts Python data into a JSON-formatted string. Note how Python False becomes false in JSON, matching JSON syntax rules.

Converting JSON to Python Objects (Deserialization)

To parse a JSON string into Python data types, use json.loads():

json_data = '{"name": "Bob", "age": 25, "is_admin": true}'
parsed_data = json.loads(json_data)
print(parsed_data)
print(type(parsed_data))
{'name': 'Bob', 'age': 25, 'is_admin': True}
<class 'dict'>

Explanation

The JSON string is turned into a Python dictionary. JSON's true becomes Python's True, and strings are decoded as Python strings.

Reading JSON from a File

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

Writing JSON to a File

data = {"language": "Python", "version": 3.10}
with open('data.json', 'w') as file:
    json.dump(data, file)

Tip

Always use a context manager (with statement) to ensure the file is properly closed after reading/writing.

Pretty-Printing JSON

To make your JSON output more readable (e.g., for logging or debugging), use indent and sort_keys parameters:

data = {"name": "Zara", "age": 22, "city": "Delhi"}
print(json.dumps(data, indent=4, sort_keys=True))
{
    "age": 22,
    "city": "Delhi",
    "name": "Zara"
}

Handling Errors While Parsing JSON

Incorrect JSON will throw an exception. Always wrap your parsing logic in a try-except block:

json_string = '{"name": "Alex", "age": 28'  # Missing closing brace

try:
    data = json.loads(json_string)
except json.JSONDecodeError as e:
    print("JSON decoding failed:", e)
JSON decoding failed: Expecting ',' delimiter: line 1 column 29 (char 28)

Common Checks and Best Practices

  • Ensure the JSON string is valid before parsing
  • Use try-except to handle malformed data
  • Use json.dump() and json.load() for file operations
  • Validate encoding types when reading non-UTF-8 files

Advanced: Custom Encoding with json.JSONEncoder

Suppose we want to encode a custom object:

import json
from datetime import datetime

class User:
    def __init__(self, name):
        self.name = name
        self.timestamp = datetime.now()

def custom_encoder(obj):
    if isinstance(obj, User):
        return {"name": obj.name, "timestamp": obj.timestamp.isoformat()}
    raise TypeError("Object not serializable")

user = User("Sam")
print(json.dumps(user, default=custom_encoder))

Summary

Whether you're building APIs, consuming web services, or simply storing structured data, JSON is a must-know skill in Python. With just a few functions from the json module, you can serialize, deserialize, and safely manipulate structured data. Remember to handle exceptions gracefully, validate data, and use pretty-printing to inspect JSON when debugging.

Mallikarjuna Mallisetty, author
About the author

Mallikarjuna Mallisetty

General programming

Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.

View LinkedIn profile ↗