Ir al contenido

05. JSON Handling

Guide to JSON integration with JavaScript, conversions, structures, and processing with fetch.

0views

JSON (JavaScript Object Notation) is a lightweight and standardized format for exchanging data between different applications. It is increasingly used in web development environments because it is simple and compatible with practically all programming languages.

Although its name includes “JavaScript” and it integrates naturally with JS, it is not tied to the language; rather, it is a universal standard for exchanging information between web applications, APIs, and other information systems.

We will use JSON as a powerful tool to enable communication between applications that "speak" different languages, such as the web frontend and the backend. We will use it extensively in communication processes with web services because it allows us to retrieve dynamic data based on the query we perform. For example:

  • Online Store: We will store and exchange product information (name, price, category, available stock).
  • Video Game Configuration: We will save levels, unlocked characters, scores, and player configuration options (language, volume, controls).
  • IoT Devices: We will configure and monitor the status of connected devices (light, temperature, energy consumption).
  • Mobile Applications: We will synchronize user data such as preferences, search history, or wishlists.
  • Social Networks: We will share data such as messages, friend lists, notifications, and privacy preferences.
  • Online Education: We will save information regarding courses, lessons, progress, and student grades.

JSON is based on two main structures:

Objetos: collections of keys and values (like a dictionary).

Arrays: ordered lists of values.

The supported data types are:

  • string → text enclosed in double quotes "”…”".
  • number → integers or decimals.
  • boolean → true or false.
  • null → empty value.
  • object → collection of keys and values.
  • array → ordered list of values.

JSON example (retrieving product information from an e-commerce site):

{
"productos": [
{
"id": 101,
"nombre": "Portátil Lenovo ThinkPad",
"descripcion": "CPU i7-13300, Memoria 32GB RAM, Disco 1TB SSD.",
"precio": 799.90,
"stock": 12,
"categorias": ["ordenadores", "portatiles", "tecnologia"]
},
{
"id": 102,
"nombre": "Smartphone Samsung Galaxy",
"descripcion": "Pantalla 6.5'', CPU Exynos 2100, 128GB de almacenamiento.",
"precio": 699.00,
"stock": 25,
"categorias": ["telefonos", "smartphones", "tecnologia"]
}
]
}

Converting JSON to JavaScript Object and vice versa

Sección titulada «Conversión de JSON a Objeto JavaScript y viceversa»

To be able to use JSON information in JavaScript, we must convert it into a JavaScript object. This can be done using the JSON.parse() function, which transforms a JSON string into an object.

To be able to send a JavaScript object as JSON, we must convert it into a string using JSON.stringify().

Conversion examples:

// Conversión de JSON a Objeto JavaScript
const textJSON = `{
"nombre": "Pepito",
"vidas": 3,
"puntos": 1200
}`;
const jugador = JSON.parse(textJSON);
console.log(jugador.nombre); // Pepito
console.log(jugador.vidas); // 3
// Conversión de Objeto JavaScript a JSON
const jugadorObjeto = {
nombre: "Pepito",
vidas: 3,
puntos: 1200
};
const textJSONConvertido = JSON.stringify(jugadorObjeto);
console.log(textJSONConvertido);

Example of how to load and process a JSON file using fetch() to extract information and store it in variables for use in the program.

{
"nivel": 1,
"maxPuntos": 100,
"maxAsteroides": 100,
"variablesJugador": {
"vidas": 3,
"velocidad": 5
},
"variablesEnemigos": {
"vidas": 1,
"velocidad": 5,
"maxEnemigos": 12
}
}
fetch('./nivel1.json')
.then(response => {
if (!response.ok) {
throw new Error('Error al cargar el archivo JSON :(');
}
return response.json();
})
.then(data => {
console.log(data);
// Procesar los datos del nivel
console.log(`Nivel: ${data.nivel}`);
console.log(`Max Puntos: ${data.maxPuntos}`);
console.log(`Max Asteroides: ${data.maxAsteroides}`);
console.log(`Vidas del Jugador: ${data.variablesJugador.vidas}`);
console.log(`Velocidad de los Enemigos: ${data.variablesEnemigos.velocidad}`);
// (Desestructuración) Aquí se pueden utilizar estos datos para configurar el juego
const { nivel, maxPuntos, maxAsteroides, variablesJugador, variablesEnemigos } = data;
console.log(nivel, maxPuntos, maxAsteroides, variablesJugador, variablesEnemigos);
// Si antes creábamos el jugador así:
// Constructor: nombre, vidas, velocidad, posicion, ancho, alto
const jugador = new Jugador("Pepito", 3, 15, {x: 100, y: 300}, 150, 100);
// Ahora hacemos uso de las variables cargadas del JSON
const jugador1 = new Jugador(
"Pepito",
variablesJugador.vidas,
variablesJugador.velocidad,
{ x: 100, y: 300 },
150,
100
);
})
.catch(error => {
console.error('Error:', error);
});