JSON in the Python Ecosystem
JSON (JavaScript Object Notation) is the standard format for data exchange between a server and a web or mobile application. As a developer, you'll constantly handle JSON when consuming REST APIs or saving configuration files. Python provides a built-in json module to convert between JSON strings and Python dictionaries/lists.
Key Terminology
- Serialization (Encoding): Converting a Python object (like a dict) into a JSON-formatted string using
json.dumps(). - Deserialization (Decoding): Converting a JSON string back into a Python object using
json.loads().
Basic Operations
The json module makes it easy to switch between types. Note that Python's True, False, and None are automatically mapped to JSON's true, false, and null.
Working with Files
When dealing with files (e.g., config.json), use the load() and dump() methods (without the 's'). These operate directly on file streams.
Data Type Mapping
| Python Type | JSON Equivalent |
|---|---|
| dict | object {} |
| list, tuple | array [] |
| str | string "" |
| int, float | number |
| True / False | true / false |
| None | null |