How to properly use json.dump in Python to save data to a file? or Why is my json.dump in Python not

14 Replies, 1104 Views

Hey! json.dump python is pretty straightforward once you get the hang of it. Here's a dead-simple example:

```python
import json

data = {"name": "Alice", "age": 25}
with open("data.json", "w") as file:
json.dump(data, file)
```

The `indent` parameter just formats the file nicely—like adding spaces for readability. Try `json.dump(data, file, indent=4)` and open the file to see the difference.

If your file's empty, make sure you're opening it in write mode ("w") and closing it properly (using `with` like above handles that for you).

Check out [Python's official docs](https://docs.python.org/3/library/json.html) for more deets!

Messages In This Thread



Users browsing this thread: 1 Guest(s)