[b]"How to properly use json.dump in Python to save data to a file?"[/b] or [b]"Why is my json.dump in Python not

14 Replies, 909 Views

Ah, json.dump python got me too at first! Here’s the deal:

```python
import json

# Your data
user = {"id": 1, "name": "Bob"}

# Dump it
with open("user.json", "w") as file:
json.dump(user, file)
```

Indent is like makeup for your json—optional but nice.

If the file’s empty, maybe the data’s not serializable (e.g., contains a `set` or custom object). Test with `print(json.dumps(user))` first!

---

Thanks everyone! Your examples cleared things up. I was missing the `with` statement—oops!

One follow-up: what if I want to append to a json file instead of overwriting? json.dump python seems to wipe the old data. Is there a way or should I just load, update, and dump again?

Also, the indent tip was gold—my files look way nicer now. Cheers!

Messages In This Thread



Users browsing this thread: 1 Guest(s)