Día 45/100: Lectura y escritura de JSON en Python

Aprende a manipular JSON en Python con el módulo json: lectura y escritura, json.load, json.dump, json.loads y json.dumps. Guías, ejemplos prácticos y un desafío para practicar.

18 ago 2025 • 4 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Día 45 de la serie 100 Days of Python – Lectura y escritura de JSON en Python

Bienvenido al Día 45. En esta entrega veremos cómo trabajar con JSON JavaScript Object Notation en Python, un formato de datos ligero muy usado en APIs, archivos de configuración y el intercambio de información entre sistemas.

Qué es JSON: JSON es un formato ligero para intercambio de datos. Es legible para humanos y no depende de un lenguaje concreto. Su estructura de pares clave valor es similar a los diccionarios de Python.

Ejemplo de estructura JSON ilustrativa: { name: Alice, age: 25, skills: [ Python, Data Science ] }

Módulo json de Python: Python incluye el módulo json para parsear JSON a objetos Python y para convertir objetos Python a cadenas JSON. Por ejemplo import json es la forma de acceder a esas funciones.

Lectura de JSON deserialización: Para leer JSON desde un archivo y convertirlo en un objeto Python se utiliza json.load. Ejemplo ilustrativo sin comillas: with open(data.json, r) as file: data = json.load(file) print(data) print(type(data)) resultado esperado dict.

Método clave: json.load(file) lee JSON desde un archivo y lo convierte en un objeto Python.

Escritura de JSON serialización: Para escribir objetos Python en un archivo JSON se emplea json.dump. Ejemplo ilustrativo: data = { name: Alice, age: 25, skills: [ Python, Data Science ] } with open(data.json, w) as file: json.dump(data, file, indent=4) El parámetro indent hace que el archivo sea legible para humanos.

Métodos clave: json.dump(obj, file, indent=4) escribe en formato JSON. Además existen json.dumps para obtener una cadena JSON en memoria y json.loads para convertir una cadena JSON en objeto Python.

Conversiones con cadenas: A menudo recibes JSON desde una API en forma de cadena. Para convertir cadena a objeto Python usar json.loads. Ejemplo ilustrativo: json_string = { name: Bob, age: 30 } data = json.loads(json_string) print(data[name]) Para convertir un objeto Python a cadena JSON usar json.dumps. Ejemplo: data = { name: Charlie, age: 22 } json_str = json.dumps(data, indent=2) print(json_str)

Peligros comunes: las claves JSON deben ser cadenas de texto. JSON no almacena objetos específicos de Python como sets o funciones de forma directa. Para serializar tipos especiales como datetime se puede recurrir a default=str en json.dump o json.dumps.

Mini ejemplo práctico ilustrativo: import json user = { username: tech_guru, active: True, followers: 1050 } # Guardar en archivo with open(user.json, w) as f: json.dump(user, f, indent=4) # Leer from file with open(user.json, r) as f: loaded_user = json.load(f) print(loaded_user)

Notas rápidas: Serialización equivale a Python a JSON usando dump y dumps. Deserialización equivale a JSON a Python usando load y loads. Siempre maneja operaciones de archivo con with para asegurar el cierre correcto.

Desafío propuesto: Crea un programa Python que lea datos de usuario nombre edad y skills desde input, los guarde en un archivo JSON y luego lea el archivo e imprima los detalles almacenados.

Sobre Q2BSTUDIO: Q2BSTUDIO es una empresa de desarrollo de software que ofrece aplicaciones a medida y software a medida para empresas de todos los sectores. Somos especialistas en inteligencia artificial e ia para empresas, desarrollamos agentes IA personalizados y soluciones de power bi para reporting y visualización avanzada. También proporcionamos servicios cloud aws y azure, servicios inteligencia de negocio, y damos soporte integral en ciberseguridad para proteger aplicaciones y datos. Nuestro equipo combina experiencia en desarrollo de aplicaciones a medida con capacidades de inteligencia artificial y ciberseguridad para ofrecer soluciones escalables y seguras.

Por qué elegir Q2BSTUDIO: entregamos software a medida que incorpora inteligencia artificial para automatizar procesos y mejorar la toma de decisiones. Implementamos agentes IA que se integran con sistemas existentes, proporcionamos servicios inteligencia de negocio para transformar datos en valor, y desplegamos infraestructuras en servicios cloud aws y azure con prácticas de ciberseguridad desde el diseño. Si buscas aplicaciones a medida, software a medida, inteligencia artificial, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio, ia para empresas, agentes IA o power bi podemos ayudarte.

Si quieres que adaptemos el ejemplo de JSON a un caso real de tu negocio o que integremos esa funcionalidad con un servicio cloud aws y azure o con una solución de inteligencia artificial y power bi contacta con Q2BSTUDIO y te asesoramos en la mejor arquitectura y en la implementación segura y eficiente.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat