Trying to manipulate a JSON with JS

Asked

Viewed 171 times

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 and JSON.stringify?

  • 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

  • The goal is just to copy the contents of the file into a new file?

  • 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?

3 answers

2

If you just want to copy the file to another:

const { createReadStream, createWriteStream } = require('fs');

createReadStream('index.json').pipe(createWriteStream('writeMe.json'));

It makes no difference being a json in this case.

From version 8.x the function fs.copyFile and copyFileSync were added:

const { copyFileSync } = require('fs');

fs.copyFileSync('index.json', 'writeMe.json');

fs.copyFile(src, dest[, flags], callback)

Asynchronously copies src to dest.

In free translation:

Asynchronously copy src for dest.


Reference: Fastest way to copy file in Node.js.

0

The problem is in assigning the recording variable, when the loop leaves the contents blank in the array...

If the goal is to delete the last character is very simple, change the following lines:

let gravador = '';
fs.readFile('index.json', 'utf8', function (err, data) {
  gravador = data.slice(0, -1);
}

0

You have to parse, so the JS can read the data smoothly.

fs.readFile('index.json', 'utf8', (error, data) => {

//caso haja erro mostra no terminal
if(error){
    console.log(error)
}

//se está tudo ok... converte o json 
let fileConvert = JSON.parse(data)

//e insere em 'gravador'
gravador.push(fileConvert)
console.log(gravador)

//converter a string para JSON
let dataConverted = JSON.stringify(gravador)

//insere o conteudo do arquivo em outro arquivo JSON
fs.writeFileSync('indexNEW.json', dataConverted, (err, result)=> {
    console.log(result)
})

})

  • The return error wave error where?

  • in case of error, will be shown an error message, I will edit better for you understand.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.