jsondecode.com logo

HomeChevronBlogChevronHow to Work with JSON in Python: json Module Complete Guide

Blog post

How to Work with JSON in Python: json Module Complete Guide

Complete guide to Python's json module — json.loads(), json.dumps(), custom encoders, datetime serialization, and reading/writing JSON files with examples.

author

Shashank Jain

Author

22/05/20260 minutes 38 seconds read
How to Work with JSON in Python: json Module Complete GuideHow to Work with JSON in Python: json Module Complete Guide

Article

Python's json Module

Python includes a built-in json module that handles JSON serialization and deserialization. No installation required.

Parse JSON from a String

import json

data = json.loads('{"name": "Alice", "age": 30}')
print(data['name'])  # Alice
print(type(data))    # dict

Convert Python to JSON String

import json

obj = {'name': 'Alice', 'age': 30, 'active': True}
json_str = json.dumps(obj, indent=2)
print(json_str)

Read JSON from a File

import json

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

Write JSON to a File

import json

data = {'users': [{'id': 1, 'name': 'Alice'}]}
with open('output.json', 'w') as f:
    json.dump(data, f, indent=2)

Handling Dates and Custom Types

from datetime import datetime
import json

# Serialize datetime
json.dumps({'created': datetime.now().isoformat()})

# Custom encoder
class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.isoformat()
        return super().default(obj)

json.dumps({'ts': datetime.now()}, cls=DateEncoder)

json.dumps() Options Reference

ParameterDefaultPurpose
indentNonePretty-print with N spaces
sort_keysFalseSort object keys alphabetically
ensure_asciiTrueEscape non-ASCII chars
separators(',', ': ')Control separators for minifying

Use the complete Python JSON guide at jsondecode.com for more examples.

Keep reading

Recent blogs

View all

If jsondecode.com saved you time, share it with your team

Free forever. No ads. No sign-up. Help other developers find it.