- Courses
- 💻Programming Languages
- 🐍Python
- File Handling & Persistence
- Working with JSON
On this page
Introduction to JSON Handling in Python
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
JSON (JavaScript Object Notation) is a standardized, text-based format used to represent structured data. It is the primary language of the internet, used by nearly every web API and configuration system to exchange information between different programming languages.
Because JSON is essentially just text, it is easy for humans to read and for computers to parse. In Python, the built-in json module provides the tools necessary to convert JSON data into Python objects (like dictionaries and lists) and vice versa.
The Core Concept: Serialization and Deserialization
Working with JSON involves two main processes:
- Deserialization (Reading): Converting JSON text into a Python object (e.g., a dictionary).
- Serialization (Writing): Converting a Python object into JSON text for storage or transmission.
The Naming Convention
The Python json module uses four primary functions. Understanding the naming convention makes them easy to remember:
- Functions ending in
s(loads,dumps) operate on Strings. - Functions without the
s(load,dump) operate on Files.
Reading JSON Data
Parsing a JSON String (json.loads)
If you receive JSON data as a string (common when working with web services), use json.loads (load string).
import json
# A string formatted as JSON
json_data = '{"username": "jdoe", "active": true, "access_level": 5}'
# Convert string to a Python dictionary
user = json.loads(json_data)
print(user["username"]) # Output: jdoe
print(type(user)) # Output: <class 'dict'>
Reading from a File (json.load)
When data is stored in a .json file, use json.load.
with open("data.json", "r", encoding="utf-8") as file:
data = json.load(file)
print(data)
Writing JSON Data
Converting to a String (json.dumps)
To convert a Python dictionary into a JSON-formatted string (for example, to send to an API), use json.dumps (dump string).
settings = {
"theme": "dark",
"notifications": True,
"recent_files": 3
}
# Convert dictionary to JSON string
json_string = json.dumps(settings)
print(json_string)
# Output: {"theme": "dark", "notifications": true, "recent_files": 3}
Saving to a File (json.dump)
To save a Python object directly to a file, use json.dump.
with open("settings.json", "w", encoding="utf-8") as file:
# indent=4 makes the file readable for humans
json.dump(settings, file, indent=4)
Handling Common Exceptions
JSON is a strict format. A missing comma, a misplaced bracket, or a single-quoted key will cause a json.JSONDecodeError. It is best practice to wrap your parsing logic in a try...except block to prevent your program from crashing when encountering invalid data.
invalid_json = '{"name": "Alice" "age": 25}' # Error: missing comma
try:
data = json.loads(invalid_json)
except json.JSONDecodeError as e:
print(f"Failed to parse JSON: {e}")
Summary Reference
GoalFunctionInput TypeOutput TypeRead Stringjson.loads()JSON StringPython ObjectRead Filejson.load()File ObjectPython ObjectWrite Stringjson.dumps()Python ObjectJSON StringWrite Filejson.dump()Python ObjectFile Object
Best Practices
- Encoding: Always use
encoding="utf-8"when opening files to support international characters. - Readability: Use the
indentparameter indumpordumpswhen creating files meant for human review. - Type Safety: Remember that JSON does not support all Python types (such as
setsorcomplexnumbers). Stick to dictionaries, lists, strings, numbers, and booleans.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Writing Files
Next
Working with CSV
-
The Core Concept: Serialization and Deserialization
- The Naming Convention
-
Reading JSON Data
- Parsing a JSON String (
json.loads) - Reading from a File (
json.load)
- Parsing a JSON String (
-
Writing JSON Data
- Converting to a String (
json.dumps) - Saving to a File (
json.dump)
- Converting to a String (
-
Handling Common Exceptions
-
Summary Reference
- Best Practices
