Working with JSON in Python
JSON (JavaScript Object Notation) is a lightweight and human-readable format for storing and exchanging data. It's the most common way web APIs send and receive information.
Python has a built-in json module that makes it easy to convert between Python dictionaries/lists and JSON strings, and to read/write JSON files.
You'll use JSON when working with APIs (like Fetch in JavaScript), saving settings, or processing data from the web.
We'll go through everything step by step with lots of examples you can run.
Importing the json Module
Always start by importing json.
Converting Python to JSON (Serialization)
Use json.dumps() to convert a Python object to a JSON string. Use json.dump() to write directly to a file.
Common options: indent for pretty printing, sort_keys for sorted keys.
Converting JSON to Python (Deserialization)
Use json.loads() for strings, json.load() for files.
Handling Non-JSON-Compatible Types
JSON only supports basic types. For dates, sets, or custom objects, provide a default function.
Error Handling with JSON
Always wrap in try/except for invalid JSON.
Real-World Example: API Data
Many APIs return JSON – you parse it to use the data.
Quick Quiz
Az anyagokat átnéztük és ellenőriztük, de hibák továbbra is előfordulhatnak. A tartalom kizárólag oktatási célt szolgál, ezért saját felelősségre használd, és szükség esetén ellenőrizd más forrásokkal is.
✨ Kérdezd Larát — a tanulási partnered
Fedezd fel a személyre szabott tanulási támogatást. Lara elmagyarázza az anyagot, összefoglalja a témákat és megválaszolja a kérdéseidet — az Go csomagtól elérhető.
Lara segít gyorsabban tanulni — kizárólag a ReadyTools Go, Plus és Max tagoknak.
