Tips and Traps¶
It is suggested that you avoid using JSON for serializing and deserializing data. Please refer to Shotcomes of JSON for detailed discussions on this. TOML and YAML are better text-based alternatives to JSON. If serialization and deserialization is done in Python only, pickle is preferred.
Even if you do want to use JSON in Python, the built-in standard library json is not necessarily a good choice. Please refer to JSON Parsing Libraries in Python for more discussions.
The json library does not throw error or given any warning if you have multiple records for the same key in the JSON file!!! This is error-prone when handling large JSON configuration files.
import json
json.load(open("data.json"))
json.dumps¶
Convert an object to a json string.
json.dump¶
Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object) using this conversion table.
Formatting¶
json.dumps(json.loads("[{}]"), indent=4, sort_keys=True)
json.dumps(json.loads(" [{ }]\n"), indent=4, sort_keys=True)
Seriallizablle Types in JSON Format¶
- int, float
- str
Non-serializable Types¶
JSON is not a good serialization format as lots of objects in Python cannot be serialized in JSON.
pickle
is a much better alternative for serializing objects.
datetime.datetime, etc.¶
datetime.datetime
, datetime.date
, datetime.timedelta
are not serializable.
A possible alternative is to use timestamp instead.
A dataclass is not JSON serializable by default.
from dataclasses import dataclass
@dataclass
class Query:
query: str = ""
timestamp: float = 0.0
table: str = ""
json.dumps([Query()])