Python JSON
Python · Working with Data
Theory
JSON (JavaScript Object Notation) is a text format for structured data, used by almost every web API and many config files. Python's json module converts between JSON text and Python objects. json.dumps(obj) (dump to string) turns a dict or list into JSON text, and json.loads(text) (load from string) parses JSON text back into Python objects. json.dump() and json.load(), without the s, do the same with files.
The mapping is natural: a JSON object becomes a dict, an array a list, a string a str, numbers int or float, true/false become True/False and null becomes None. json.dumps({'name': 'Asha'}) gives the string '{"name": "Asha"}' - note JSON requires double quotes. Use indent=2 for readable output. Some Python types, such as datetime or set, are not JSON-serializable and raise TypeError.
Why we use it
JSON is the common language for exchanging data between programs. The json module lets your Python code read API responses and config files and send data out in a format any system understands.
When to use it
Use json for API payloads, config files and saving simple nested data. For large tables pandas (pd.read_json, CSV, Parquet) is better, and for saving arbitrary Python objects pickle exists, but never unpickle untrusted data.
How it works
- Have a Python dict or JSON text
- Python -> JSON? Yes: json.dumps(obj) -> JSON string. No: json.loads(text) -> Python object.
- Working with a file? Yes: Use json.dump / json.load on it. No: Keep the string in memory.
- Data ready to send, store or use
Syntax
import json
json.dumps(obj)
json.loads(text)Example
data = {'name': 'Asha'}
json.dumps(data)Key points
- dumps() converts Python -> JSON string
- loads() parses JSON string -> Python object
- dump()/load() work with files directly
- indent=2 pretty-prints the output
- datetime and set are not JSON-serializable by default