escribir / agregar datos en un archivo JSON usando node.js


Estoy tratando de escribir un archivo JSON usando el nodo de datos de bucle eg

var jsonfile = require('jsonfile');
for (i=0; i <11 ; i++){
   jsonfile.writeFile('loop.json', "id :" + i + " square :" + i*i);
}

Salida en bucle.json es

id :1 square : 1

Pero quiero un archivo de salida como este (abajo) y también si corro ese código de nuevo debería agregar esa nueva salida como elementos en el mismo archivo JSON existente

{
  "table": [
    {
      "Id ": 1,
      "square ": 1
    },
    {
      "Id ": 2,
      "square ": 3
    },
    {
      "Id ": 3,
      "square ": 9
    },
    {
      "Id ": 4,
      "square ": 16
    },
    {
      "Id ": 5,
      "square ": 25
    },
    {
      "Id ": 6,
      "square ": 36
    },
    {
      "Id ": 7,
      "square ": 49
    },
    {
      "Id ": 8,
      "square ": 64
    },
    {
      "Id ": 9,
      "square ": 81
    },
    {
      "Id ": 10,
      "square ": 100
    }
  ]
}

Quiero usar el mismo archivo que creé 1a vez, pero cada vez que ejecute ese código, nuevos elementos deben agregar en ese mismo archivo

var fs = require('fs');

var obj = {
   table: []
};

fs.exists('myjsonfile.json', function(exists){
    if(exists){
        console.log("yes file exists");
        fs.readFile('myjsonfile.json', function readFileCallback(err, data){
        if (err){
            console.log(err);
        } else {
        obj = JSON.parse(data); 
        for (i=0; i<5 ; i++){
        obj.table.push({id: i, square:i*i});
        }
        var json = JSON.stringify(obj); 
        fs.writeFile('myjsonfile.json', json); 
        }});
    } else {
        console.log("file not exists")
        for (i=0; i<5 ; i++){
        obj.table.push({id: i, square:i*i});
        }
        var json = JSON.stringify(obj);
        fs.writeFile('myjsonfile.json', json);
        }
    });
Author: Philip Kirkbride, 2016-04-26

5 answers

Si este archivo json no se vuelve demasiado grande con el tiempo, debe probar:

  1. Crear un objeto javascript con la matriz de tabla en él

    var obj = {
       table: []
    };
    
  2. Agregue algunos datos como

    obj.table.push({id: 1, square:2});
    
  3. Conviértalo de un objeto a cadena con stringify

    var json = JSON.stringify(obj);
    
  4. Use fs para escribir el archivo en el disco

    var fs = require('fs');
    fs.writeFile('myjsonfile.json', json, 'utf8', callback);
    
  5. Si desea agregarlo, lea el archivo json y conviértalo de nuevo en un objeto

    fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
        if (err){
            console.log(err);
        } else {
        obj = JSON.parse(data); //now it an object
        obj.table.push({id: 2, square:3}); //add some data
        json = JSON.stringify(obj); //convert it back to json
        fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back 
    }});
    

Esto trabajará para los datos grandes como 100 MB máximo con eficacia. Por encima de este límite, debe utilizar un motor de base de datos.

ACTUALIZACIÓN:

Cree una función que devuelva la fecha actual (año+mes+día) como una cadena. Cree el archivo llamado esta cadena+.json. el módulo fs tiene una función que puede comprobar la existencia del archivo llamado fs.stat (path, callback). Con esto, puede comprobar si el archivo existe. Si existe, use la función read si no lo es, use la función create. Utilice la cadena de fecha como el ruta porque el archivo será nombrado como la fecha de hoy+.json. la devolución de llamada contendrá un objeto stats que será null si el archivo no existe.

 198
Author: kailniris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-31 16:08:53

Por favor, pruebe el siguiente programa. Usted podría estar esperando esta salida.

var fs = require('fs');

var data = {}
data.table = []
for (i=0; i <26 ; i++){
   var obj = {
       id: i,
       square: i * i
   }
   data.table.push(obj)
}
fs.writeFile ("input.json", JSON.stringify(data), function(err) {
    if (err) throw err;
    console.log('complete');
    }
);

Guarde este programa en un archivo javascript, por ejemplo, cuadrado.js.

Luego ejecute el programa desde el símbolo del sistema usando el comando node square.js

Lo que hace es, simplemente sobrescribir el archivo existente con un nuevo conjunto de datos, cada vez que ejecuta el comando.

Feliz Codificación.

 8
Author: Jacob Nelson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-26 06:15:39

Debe leer el archivo, cada vez que desee agregar una nueva propiedad al json, y luego agregar las nuevas propiedades

var fs = require('fs');
fs.readFile('data.json',function(err,content){
  if(err) throw err;
  var parseJson = JSON.parse(content);
  for (i=0; i <11 ; i++){
   parseJson.table.push({id:i, square:i*i})
  }
  fs.writeFile('data.json',JSON.stringify(parseJson),function(err){
    if(err) throw err;
  })
})
 5
Author: Zamboney,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-26 06:13:11

Para formatear jsonfile da spaces opción que puede pasar como un parámetro:

   jsonfile.writeFile(file, obj, {spaces: 2}, function (err) {
         console.error(err);
   })

O utilizar jsonfile.spaces = 4. Lea los detalles aquí.

No sugeriría escribir en archivo cada vez en el bucle, en lugar de construir el objeto JSON en el bucle y escribir en archivo fuera del bucle.

var jsonfile = require('jsonfile');
var obj={
     'table':[]
    };

for (i=0; i <11 ; i++){
       obj.table.push({"id":i,"square":i*i});
}
jsonfile.writeFile('loop.json', obj, {spaces:2}, function(err){
      console.log(err);
});
 3
Author: avck,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-26 06:45:48

El ejemplo anterior también es correcto, pero proporciono un ejemplo simple:

var fs = require("fs");
var sampleObject = {
    name: 'pankaj',
    member: 'stack',
    type: {
        x: 11,
        y: 22
    }
};

fs.writeFile("./object.json", JSON.stringify(sampleObject, null, 4), (err) => {
    if (err) {
        console.error(err);
        return;
    };
    console.log("File has been created");
});
 0
Author: Pankaj Chauhan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-13 11:31:21