95 lines
2.6 KiB
JavaScript
95 lines
2.6 KiB
JavaScript
class JSONUtils {
|
|
constructor(data) {
|
|
if (typeof data !== 'object' || data === null) {
|
|
throw new Error('Data must be a valid JSON object');
|
|
}
|
|
this.data = data;
|
|
}
|
|
|
|
getValue(path) {
|
|
const keys = path.split('.');
|
|
let result = this.data;
|
|
|
|
try {
|
|
for (const key of keys) {
|
|
if (result[key] === undefined) {
|
|
throw new Error(`Property '${key}' does not exist`);
|
|
}
|
|
result = result[key];
|
|
}
|
|
return result;
|
|
} catch (error) {
|
|
console.error(error.message);
|
|
return null; // Devuelve null si hay un error
|
|
}
|
|
}
|
|
|
|
setValue(path, value) {
|
|
const keys = path.split('.');
|
|
let current = this.data;
|
|
|
|
try {
|
|
keys.forEach((key, index) => {
|
|
if (index === keys.length - 1) {
|
|
current[key] = value;
|
|
} else {
|
|
if (current[key] === undefined) {
|
|
current[key] = {}; // Crea objeto si no existe
|
|
}
|
|
current = current[key];
|
|
}
|
|
});
|
|
} catch (error) {
|
|
console.error(`Error setting value: ${error.message}`);
|
|
}
|
|
}
|
|
|
|
updateValue(path, value) {
|
|
const currentValue = this.getValue(path);
|
|
if (currentValue !== null) {
|
|
this.setValue(path, value);
|
|
} else {
|
|
console.error(`Cannot update: Property at '${path}' does not exist`);
|
|
}
|
|
}
|
|
|
|
deleteValue(path) {
|
|
const keys = path.split('.');
|
|
let current = this.data;
|
|
|
|
try {
|
|
keys.forEach((key, index) => {
|
|
if (index === keys.length - 1) {
|
|
delete current[key];
|
|
} else {
|
|
if (current[key] === undefined) {
|
|
throw new Error(`Property '${key}' does not exist`);
|
|
}
|
|
current = current[key];
|
|
}
|
|
});
|
|
} catch (error) {
|
|
console.error(`Error deleting value: ${error.message}`);
|
|
}
|
|
}
|
|
|
|
saveToFile() {
|
|
try {
|
|
fs.writeFileSync(this.filePath, JSON.stringify(this.data, null, 2));
|
|
console.log('Datos guardados exitosamente en el archivo.');
|
|
} catch (error) {
|
|
console.error('Error al guardar los datos:', error.message);
|
|
}
|
|
}
|
|
|
|
getJSON() {
|
|
return this.data;
|
|
}
|
|
|
|
printJSON() {
|
|
console.log(JSON.stringify(this.data, null, 2));
|
|
}
|
|
}
|
|
|
|
module.exports = JSONUtils;
|