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
Hemos revisado y comprobado los materiales, pero aún pueden existir errores. El contenido se ofrece únicamente con fines educativos, así que úsalo bajo tu propia responsabilidad y verifica con otras fuentes si es necesario.
✨ Pregunta a Lara — tu compañera de estudio con IA
Desbloquea soporte de aprendizaje personalizado. Lara puede explicar lecciones, resumir temas y responder tus preguntas — disponible desde el plan Go y superiores.
Lara te ayuda a aprender más rápido — exclusivo para los miembros ReadyTools Go, Plus y Max.


