Why is json.dump not writing to my file correctly? or How do I properly format data before using json

16 Replies, 1082 Views

Ugh, been there. json.dump hates certain Python types—like sets or datetime. If your data’s a "hot mess," try converting non-standard types first.

For example:
```python
import json
from datetime import datetime

data = {"time": datetime.now()}
# This’ll fail! Instead, do:
data["time"] = str(data["time"])
json.dump(data, f)
```
Or use `default=str` in json.dump, but it’s a band-aid. For heavy lifting, check out `orjson`—way faster and less picky.

Messages In This Thread



Users browsing this thread: 1 Guest(s)