1.JSON
json.dumps(obj) turns a Python dict, list, str, int, float, bool, or None into JSON text. json.loads(text) turns JSON text back into those same Python types.
Key features
- json.dumps(obj) returns a str; json.dump(obj, file) writes straight to a file object
- json.loads(text) returns a str; json.load(file) reads straight from a file object
- Python True/False/None become JSON true/false/null, and back, automatically
- dumps(obj, indent=2) pretty-prints; without indent, output is one compact line
- A type dumps cannot handle (datetime, set, a custom object) raises TypeError, not a silent conversion
json — the four functions and the type mapping
- Python dict — {"user_id": 4821, ...}
- json.dumps() — Python object -> JSON text
- JSON text — a plain str, ready to write or send
Command
import json
text = json.dumps(obj, indent=2) # Python -> JSON string
obj = json.loads(text) # JSON string -> Pythonjson.dumps/loads convert between JSON text and dict/list/str/int/float/bool/None only — anything else needs default=str or a manual conversion first.