JSON CRUD Operations in Python
This Python script demonstrates how to perform basic CRUD (Create, Read, Update, Delete) operations on a JSON file. It uses a simple JSON file to store data and provides functions to add, remove, update, and display all elements in the file.
Step-by-Step Explanation
1. Importing the JSON Module
import json
We start by importing the json
module, which provides functions to encode and decode JSON data.
2. Defining Constants
# Ruta del archivo JSON donde se almacenarán los datos
ARCHIVO_JSON = 'datos.json'
We define a constant ARCHIVO_JSON
to specify the path to the JSON file where we'll store our data.
3. Loading Data from the JSON File
# Función para cargar los datos desde el archivo JSON
def cargar_datos():
try:
with open(ARCHIVO_JSON, 'r') as f:
datos = json.load(f)
except FileNotFoundError:
datos = []
return datos
The cargar_datos()
function is used to load data from the JSON file. It opens the file in read mode ('r'
) and uses the json.load()
function to parse the JSON data into a Python dictionary. If the file doesn't exist, it creates an empty list to avoid errors.
4. Saving Data to the JSON File
# Función para guardar los datos en el archivo JSON
def guardar_datos(datos):
with open(ARCHIVO_JSON, 'w') as f:
json.dump(datos, f, indent=4)
The guardar_datos()
function is used to save data to the JSON file. It opens the file in write mode ('w'
) and uses the json.dump()
function to convert the Python dictionary back into JSON format. The indent=4
argument is used to make the JSON output more readable.
5. Adding a New Element
# Función para agregar un nuevo elemento
def agregar_elemento(nombre, imagen, enlace):
datos = cargar_datos()
nuevo_elemento = {
'Nombre': nombre,
'Imagen': imagen,
'Enlace': enlace
}
Generated by [BlackboxAI](https://www.blackbox.ai)