Sto cercando di scrivere un file JSON usando il nodo dai dati del ciclo, ad es:
let jsonFile = require('jsonfile');
for (i = 0; i < 11; i++) {
jsonFile.writeFile('loop.json', "id :" + i + " square :" + i * i);
}
outPut in loop.json è:
id :1 square : 1
ma voglio un file di output come questo (sotto) e anche se eseguo di nuovo quel codice dovrebbe aggiungere quel nuovo output come elementi nello stesso file JSON esistente:
{
"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
}
]
}
Voglio usare lo stesso file che ho creato la prima volta ma ogni volta che eseguo quel codice i nuovi elementi dovrebbero essere aggiunti in quello stesso file
const fs = require('fs');
let 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
});
}
let 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
});
}
let json = JSON.stringify(obj);
fs.writeFile('myjsonfile.json', json);
}
});
Se questo file json non diventerà troppo grande nel corso del tempo si dovrebbe provare:
Creare un oggetto javascript con l'array di tabelle
var obj = {
tabella: []
};
Aggiungere alcuni dati come
obj.table.push({id: 1, square:2});
Convertirlo da oggetto a stringa con stringify
var json = JSON.stringify(obj);
usare fs per scrivere il file su disco
var fs = require('fs');
fs.writeFile('myjsonfile.json', json, 'utf8', callback);
se vuoi aggiungerlo leggi il file json e riconvertilo in un oggetto
fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
se (err){
console.log(err);
} else {
obj = JSON.parse(data); //ora è un oggetto
obj.table.push({id: 2, square:3}); //aggiungere alcuni dati
json = JSON.stringify(obj); //convertirlo di nuovo in json
fs.writeFile('myjsonfile.json', json, 'utf8', callback); // riscriverlo
}});
Questo funzionerà per dati grandi al massimo 100 MB in modo efficace. Oltre questo limite, si dovrebbe usare un motore di database.
AGGIORNARE:
Creare una funzione che restituisca la data corrente (anno+mese+giorno) come stringa. Create il file chiamato questa stringa + .json. il modulo fs ha una funzione che può controllare l'esistenza del file chiamata fs.stat(path, callback). Con questo, potete controllare se il file esiste. Se esiste, usate la funzione read, se non esiste, usate la funzione create. Usate la stringa della data come percorso perché il file sarà chiamato come la data odierna + .json. la callback conterrà un oggetto stats che sarà nullo se il file non esiste.
Per favore provate il seguente programma. Potresti aspettarti questo output.
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');
}
);
Salva questo programma in un file javascript, diciamo square.js.
Poi esegui il programma dal prompt dei comandi usando il comando node square.js
.
Quello che fa è semplicemente sovrascrivere il file esistente con un nuovo set di dati, ogni volta che si esegue il comando.
Felice codifica.
dovresti leggere il file, ogni volta che vuoi aggiungere una nuova proprietà al json, e poi aggiungere le nuove proprietà
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;
})
})