Python5 min read
Python JSON Handling
Work with JSON data in Python.
Michael Brown
December 18, 2025
0.0k0
Handle JSON data easily.
Python to JSON
```python import json
person = { "name": "Alice", "age": 28, "city": "Portland" }
Convert to JSON string json_string = json.dumps(person) print(json_string) # {"name": "Alice", "age": 28, "city": "Portland"}
Pretty print json_pretty = json.dumps(person, indent=2) print(json_pretty) ```
JSON to Python
```python import json
json_string = '{"name": "Bob", "age": 30}'
Convert to Python dict person = json.loads(json_string) print(person["name"]) # Bob ```
Read JSON File
```python import json
Read from file with open("data.json", "r") as file: data = json.load(file) print(data) ```
Write JSON File
```python import json
data = { "users": [ {"name": "Tom", "city": "Austin"}, {"name": "Sarah", "city": "Miami"} ] }
Write to file with open("users.json", "w") as file: json.dump(data, file, indent=2) ```
Remember
- dumps() for string, dump() for file - loads() for string, load() for file - Use indent for readable JSON
#Python#Intermediate#JSON