Python Tutorial: JSON in Python
Speak the language of APIs. json.loads, json.dumps, nested data, and custom serializers.
JSON is everywhere
REST APIs return JSON. Config files are JSON. You will read and write JSON every single day as a Python developer.
Python's `json` module makes it trivial. Ten steps.
What you'll learn in this Python json in python tutorial
This interactive Python tutorial has 8 hands-on exercises. Estimated time: 16 minutes.
- JSON — the language APIs speak — APIs respond in JSON. Configuration files are often JSON. Even your browser's local storage uses JSON.
- json.loads — parse any API response — When an API responds, you get a string of JSON. `json.loads()` parses it into Python objects:
- json.dumps — turn Python into JSON — `json.dumps()` does the reverse — converts Python objects to JSON text.
- Write JSON to a file — To save data to a file, use `json.dump()` (no 's') — dumps directly to a file object:
- Nested JSON — go as deep as you need — Real API responses are often deeply nested. You can chain key access as deep as needed.
- JSONDecodeError — handle bad JSON — What if the server sends you malformed JSON? Maybe it's an HTML error page instead of JSON. `json.loads()` raises `json.…
- Custom serialisation — handle non-JSON types — Python's `datetime` and custom objects can't be serialised to JSON by default:
- Build a settings manager — Final challenge — no starter code.
Python JSON in Python concepts covered
- JSON is everywhere