JSON (JavaScript Object Notation) is a lightweight data-interchange format often used for exchanging data between systems. Python offers robust tools for working with JSON, making it simple to parse, manipulate, and generate JSON data. In this quick guide, you’ll learn how to use Python’s json
module to handle JSON effectively.
Contents
What is JSON?
JSON is a text-based data format composed of key-value pairs (like Python dictionaries) and arrays (similar to Python lists). Here’s an example of JSON data:
{ "name": "John", "age": 25, "skills": ["Python", "Machine Learning"], "is_active": true }
Working with JSON in Python
The built-in json
module provides easy methods to handle JSON.
1. Parsing JSON (Loading JSON Strings)
You can convert a JSON-formatted string into a Python object using json.loads()
.
import json # JSON string json_data = '{"name": "John", "age": 25, "skills": ["Python", "Machine Learning"]}' # Parse JSON to Python dictionary data = json.loads(json_data) print(data["name"]) # Output: Alice
2. Reading JSON from a File
Use json.load()
to read JSON data directly from a file.
# Reading JSON from a file with open('data.json', 'r') as file: data = json.load(file) print(data)
3. Converting Python Objects to JSON
You can convert Python objects (e.g., dictionaries, lists) into JSON strings using json.dumps()
.
# Python object data = { "name": "John", "age": 25, "skills": ["Python", "Machine Learning"] } # Convert Python object to JSON string json_string = json.dumps(data, indent=4) # Pretty-print with indentation print(json_string)
4. Writing JSON to a File
To save JSON data to a file, use json.dump()
.
# Writing JSON to a file with open('output.json', 'w') as file: json.dump(data, file, indent=4)
5. Handling JSON Arrays
JSON arrays map directly to Python lists. You can parse and manipulate them easily.
json_array = '[1, 2, 3, 4, 5]' data = json.loads(json_array) # Access elements print(data[2]) # Output: 3
6. Dealing with Special Data Types
Non-string dictionary keys in Python are converted to strings in JSON.
Data Type Mappings
JSON Data Type | Python Data Type |
---|---|
object (e.g., {}) | dict |
array (e.g., []) | list |
string (e.g., "a") | str |
number (integer) | int |
number (float) | float |
true | True |
false | False |
null | None |
Example:
import json json_string = '{"name": "John", "age": 25, "active": true, "phoneNumber": null, "score": 93.57, "hobbies": ["Speed-cubing", "Travel"], "skills": {"Python": 10, "ML": 8, "JavaScript": 5} }' data = json.loads(json_string) print(f"Name: {data['name']}, Type: {type(data['name'])}") print(f"Age: {data['age']}, Type: {type(data['age'])}") print(f"Active: {data['active']}, Type: {type(data['active'])}") print(f"Phone Number: {data['phoneNumber']}, Type: {type(data['phoneNumber'])}") print(f"Score: {data['score']}, Type: {type(data['score'])}") print(f"Hobbies: {data['hobbies']}, Type: {type(data['hobbies'])}") print(f"Skills: {data['skills']}, Type: {type(data['skills'])}")
Output
Name: John, Type: <class 'str'> Age: 25, Type: <class 'int'> Active: True, Type: <class 'bool'> Phone Number: None, Type: <class 'NoneType'> Score: 93.57, Type: <class 'float'> Hobbies: ['Speed-cubing', 'Travel'], Type: <class 'list'> Skills: {'Python': 10, 'ML': 8, 'JavaScript': 5}, Type: <class 'dict'>
Note how data types are automatically inferred when accessing the JSON elements.
Common Errors
Invalid JSON Format
Ensure your JSON string/file adheres to JSON syntax rules.
File Not Found
When reading a file, double-check the file path.
TypeError
You cannot serialize unsupported data types (like custom Python objects) without customizing serialization.
Conclusion
JSON is an essential format for data exchange, and Python’s json
module makes it incredibly easy to work with. Whether you’re parsing data from APIs, reading JSON files, or saving structured data, these techniques will help you handle JSON efficiently in Python.
Mastering JSON is a fundamental skill for any Python developer working with web services, data pipelines, or modern application development. Happy coding!