How to Use json Module in Python: Syntax and Examples
Use the
json module in Python to convert Python objects to JSON strings with json.dumps() and parse JSON strings back to Python objects with json.loads(). You can also read from and write to files using json.dump() and json.load().Syntax
The json module provides functions to convert between Python objects and JSON format.
json.dumps(obj): Converts a Python objectobjto a JSON string.json.loads(json_string): Parses a JSON string back into a Python object.json.dump(obj, file): Writes a Python object as JSON to a file.json.load(file): Reads JSON from a file and converts it to a Python object.
python
import json # Convert Python object to JSON string json_string = json.dumps({'name': 'Alice', 'age': 30}) # Convert JSON string back to Python object python_obj = json.loads(json_string) # Write Python object to a file as JSON with open('data.json', 'w') as f: json.dump({'name': 'Alice', 'age': 30}, f) # Read JSON from a file and convert to Python object with open('data.json', 'r') as f: data = json.load(f)
Example
This example shows how to convert a Python dictionary to a JSON string and back, then save it to a file and read it again.
python
import json person = {'name': 'Bob', 'age': 25, 'city': 'New York'} # Convert to JSON string json_str = json.dumps(person) print('JSON string:', json_str) # Convert JSON string back to Python dict person_dict = json.loads(json_str) print('Python dict:', person_dict) # Save JSON to file with open('person.json', 'w') as file: json.dump(person, file) # Load JSON from file with open('person.json', 'r') as file: loaded_person = json.load(file) print('Loaded from file:', loaded_person)
Output
JSON string: {"name": "Bob", "age": 25, "city": "New York"}
Python dict: {'name': 'Bob', 'age': 25, 'city': 'New York'}
Loaded from file: {'name': 'Bob', 'age': 25, 'city': 'New York'}
Common Pitfalls
Common mistakes when using the json module include:
- Trying to serialize objects that are not supported by JSON, like sets or custom classes, without converting them first.
- Confusing
json.dumps()(returns a string) withjson.dump()(writes to a file). - Forgetting to open files in the correct mode (
'w'for writing,'r'for reading). - Not handling exceptions when parsing invalid JSON strings.
python
import json # Wrong: Trying to dump a set directly try: json.dumps({1, 2, 3}) except TypeError as e: print('Error:', e) # Right: Convert set to list first json_str = json.dumps(list({1, 2, 3})) print('JSON string:', json_str)
Output
Error: Object of type set is not JSON serializable
JSON string: [1, 2, 3]
Quick Reference
Here is a quick summary of the main json module functions:
| Function | Description |
|---|---|
| json.dumps(obj) | Convert Python object to JSON string |
| json.loads(json_string) | Parse JSON string to Python object |
| json.dump(obj, file) | Write Python object as JSON to a file |
| json.load(file) | Read JSON from a file and convert to Python object |
Key Takeaways
Use json.dumps() to convert Python objects to JSON strings.
Use json.loads() to parse JSON strings back to Python objects.
Use json.dump() and json.load() to work with JSON files.
Only JSON-serializable Python objects can be converted directly.
Always open files in the correct mode when reading or writing JSON.