How to Read and Parse a JSON File in Python
Learn how to read, parse, and load JSON files in Python using the built-in json module. Master converting JSON strings to dictionaries and vice versa.
Explanation
JSON (JavaScript Object Notation) is the most popular data format for APIs, configuration files, and data storage. Python comes with a built-in `json` module that makes it incredibly simple to read, parse, and write JSON data. Since JSON objects map perfectly to Python dictionaries, and JSON arrays map to Python lists, working with JSON feels native.
To read JSON from an external file, you use the `json.load()` function, which parses a file stream and translates the JSON structures into Python data types. If the JSON data is already loaded in memory as a string, you use the `json.loads()` function (the 's' stands for string) instead. Selecting the correct function prevents parser crashes.
When working with JSON, it is best practice to handle encoding and potential formatting errors. Using `encoding="utf-8"` within the `open()` statement protects your script from failing on special characters. Wrapping file operations in a `try-except` block catching `json.JSONDecodeError` ensures your app degrades gracefully if the JSON file is malformed.
Step-by-Step Implementation
- 1
Import the built-in json module in your script.
- 2
Open the JSON file using with open("filename.json", "r", encoding="utf-8") as file.
- 3
Pass the file object to json.load(file) to parse the contents into a Python dictionary.
- 4
Use json.loads(string_data) if you need to parse a raw JSON string already loaded in memory.
Code Example
This code demonstrates writing a sample JSON file, reading and parsing it back into a Python dictionary, and handling a JSON string.
import json
# Let's write a mock JSON file first
sample_data = {
"user": "developer123",
"skills": ["python", "javascript", "sql"],
"active": True
}
with open("data.json", "w", encoding="utf-8") as f:
json.dump(sample_data, f, indent=4)
# 1. Reading from a JSON file (using json.load)
with open("data.json", "r", encoding="utf-8") as file:
data_from_file = json.load(file)
print("File Content type:", type(data_from_file).__name__)
print("User skill list:", data_from_file["skills"])
# 2. Reading from a JSON string (using json.loads)
json_string = '{"host": "localhost", "port": 5432, "ssl": false}'
data_from_str = json.loads(json_string)
print("\nString Content type:", type(data_from_str).__name__)
print("Database host:", data_from_str["host"])File Content type: dict
User skill list: ['python', 'javascript', 'sql']
String Content type: dict
Database host: localhostFrequently Asked Questions
What is the difference between json.load() and json.loads()?
json.load() accepts a file-like stream object (reading from disk), whereas json.loads() accepts a standard string or bytes object containing JSON content (reading from memory).
How do I handle JSON serialization errors for custom classes?
Python's json module cannot serialize custom class instances by default. You must provide a custom encoder class extending json.JSONEncoder, or extract the instance's attributes into a dictionary using a helper method first.
Related How-To Guides
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python File I/O
Learn how to read and write files in Python. Master open(), read(), write(), and context managers to handle file operations securely without resource leaks.
Python File Operations
Quick reference for reading and writing files in Python. Master open modes, context managers, and reading line-by-line.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.