🐍 JSON with Python – Encode, Decode, and Handle JSON Easily (2025 Guide)
Introduction – Why Use JSON in Python?
JSON (JavaScript Object Notation) is the universal format for data exchange, and Python’s built-in json module makes it extremely simple to read, write, and manipulate JSON. Whether you’re working with REST APIs, configuration files, or storing structured data, JSON is an essential part of any Python developer’s toolkit.
In this guide, you’ll learn:
- How to encode (serialize) and decode (deserialize) JSON in Python
- Real-world examples using dictionaries and lists
- How to read/write JSON from/to files
- Best practices and error handling tips
Importing Python’s JSON Module
Python includes a standard library called json—no installation required.
import json
Encoding Python Data to JSON
Example – Convert Dictionary to JSON String
import json
user = {
"name": "Alice",
"age": 28,
"isAdmin": False
}
json_data = json.dumps(user)
print(json_data)
Output:
{"name": "Alice", "age": 28, "isAdmin": false}
✔️ json.dumps() converts a Python dictionary into a JSON-formatted string.
✔️ Boolean False becomes false in JSON.
Decoding JSON to Python Data
Example – Convert JSON String to Dictionary
import json
json_string = '{"name": "Bob", "age": 35, "isAdmin": true}'
data = json.loads(json_string)
print(data["name"]) # Output: Bob
✔️ json.loads() parses a JSON string into a Python dictionary.
✔️ JSON true/false becomes Python True/False.
Working with JSON Files
Write JSON to a File
import json
user = {"name": "Eve", "email": "eve@example.com"}
with open("user.json", "w") as f:
json.dump(user, f)
Read JSON from a File
import json
with open("user.json", "r") as f:
data = json.load(f)
print(data["email"]) # Output: eve@example.com
✔️ json.dump() and json.load() are used for file operations.
✔️ Automatically handles file streams with dictionaries/lists.
Pretty Print JSON Output
print(json.dumps(user, indent=4))
Output:
{
"name": "Eve",
"email": "eve@example.com"
}
Makes JSON output easier to read and debug.
Error Handling with JSON
Example – Invalid JSON Catch
try:
json.loads('{"name": "Eve", "age": }')
except json.JSONDecodeError as e:
print("Invalid JSON:", e)
Output:
Invalid JSON: Expecting value: line 1 column 27 (char 26)
Always catch JSONDecodeError when working with external data.
JSON Conversion Mapping (Python ↔ JSON)
| Python Type | JSON Equivalent |
|---|---|
dict | object |
list, tuple | array |
str | string |
int, float | number |
True / False | true / false |
None | null |
Summary – Recap & Next Steps
Python’s json module is powerful, built-in, and flexible—perfect for everything from API consumption to data storage. Understanding how to work with JSON is crucial for modern Python developers.
Key Takeaways:
- Use
json.dumps()andjson.loads()for strings - Use
json.dump()andjson.load()for files - Handle decoding errors safely with try-except
- Format output using
indent=4for readability
Real-world use:
Used in web scraping, data processing, REST APIs, configuration files, and machine learning pipelines.
FAQ – JSON with Python
What’s the difference between dumps() and dump() in Python?
dumps() returns a JSON string, while dump() writes to a file.
How do I convert a JSON string to a Python object?
Use json.loads() to convert a JSON string into a dictionary or list.
Can I store JSON in a Python file?
Yes, use json.dump() to write data to .json files and json.load() to read it back.
Is JSON built-in in Python?
Yes. The json module is part of Python’s standard library (no installation needed).
Share Now :
