2
I’m trying to take a data from the json file and copy it to another JSON file using Javascript, but I never did that I have this JS code:
let fs = require("fs")
let gravador = []
fs.readFile('index.json', 'utf8', function (err, data) {
for (let i = 0; i < data.length; i++) {
if (data[i] == "]") {
gravador[i] = ""
console.log(gravador[i])
}
else{
if(data[i]!= ','){
gravador[i] = data[i]
}
}
}
fs.writeFile('writeMe.json', gravador , function(err, result) {
if(err) console.log('error', err);
});
});
I want to copy this JSON to another file:
[
{
"nome": "Fulano",
"idade": 90
},
{
"nome": "Ciclano",
"idade": 45
}
]
Deleting the last character [
, but the file creates a JSON full of commas, so:
[,
,
, , , , ,{, ,
,
, , , , , , , , ,",n,o,m,e,",:, ,",F,u,l,a,n,o,",,
,
, , , , , , , , ,",i,d,a,d,e,",:, ,9,0, ,
,
, , , , ,},,
,
, , , , ,{, ,
,
, , , , , , , , , , , , ,",n,o,m,e,",:, ,",C,i,c,l,a,n,o,",, ,
,
, , , , , , , , , , , , ,",i,d,a,d,e,",:, ,4,5, ,
,
, , , , ,},
,
,,
,
,
,
Can someone explain this to me?
Have you tried using the functions
JSON.parse
andJSON.stringify
?– Luiz Felipe
Dude, I already tried to put JSON.parse there when assigning the value to the write variable and it was like this recorder[i] = JSON.parse(date[i]) but I got this error: Syntaxerror: Unexpected end of JSON input at JSON.parse (<Anonymous>) and using: recorder[i] = JSON.stringify(date[i]) n change mt thing that comma situation just got all in one line can’t understand the pq of those commas much as solving :S
– Lucas Brum
The goal is just to copy the contents of the file into a new file?
– MatheusPedro
Hi Lucas... Let me get this straight: you have 2 Jsons and you want to add the contents of one of them inside the other? you can show the contents of the destination file?
– Sergio