JSON (JavaScript Object Notation) is a lightweight text format used to represent data. It’s widely used in REST APIs, configuration files, and databases such as MongoDB.
Running the script
Save the code into a file called json_example.py and run it with:
python json_example.py
JSON structure
JSON works with objects {} and arrays []. Values can be strings, numbers, booleans, null, objects, or arrays. Example:
[
{
"nombre_alumno": "Nil",
"apellido1": "Medrano",
"fecha_entrada": "2024-01-26",
"completa": true,
"notas": [10, 10, 10, 10, 9, 10, 10],
"observaciones": "Sample observation 1"
}
]
Reading JSON from a file
Using Python’s json module:
import json
with open("insert.json", "r", encoding="utf-8") as f:
data = json.load(f)
for student in data:
print(student["nombre_alumno"], student["notas"])
Writing JSON to a file
nuevo_dato = {"nombre": "Ana", "nota": 8}
data.append(nuevo_dato)
with open("salida.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
Converting strings to JSON and back
json.loads() converts a string into a dictionary/list. json.dumps() does the opposite. This is useful when you receive JSON over the network (for example, from an API).
