Home > Net >  Parsing Json data from a file
Parsing Json data from a file

Time:07-18

I am building a Node JS application that reads file that contains array of Json objects, and displays it on a table. I need to parse the JSON data array. sample json data:

[{"name":"Ken", "Age":"25"},{"name":"Pulsar", "Age":30}]

I have used the following to read from file and pass it into another json object:

const fileRead = fs.readFileSync("/Users/mken/Desktop/Node JS/DATA-TABLE/public/files/data.json", (err, data)=>{
console.log(JSON.parse(data))
return JSON.parse(data);

});

console.log(fileRead)

The expected output is array of JSON objects. However, when I console.log the fileRead, I do not get intended output:output

I further intend to iterate through the data read above and pass it to a JSON object:

const data = {headers:["Name", "Age"], rows: fileRead.foreach((row)=>{return row.name, row.age];})}

Please check and advise.

CodePudding user response:

const fs = require('fs');

// Thanks to: https://nodejs.dev/learn/reading-files-with-nodejs
try {
  const data = fs.readFileSync('test.txt', 'utf8');
  console.log(data);
  const json = JSON.parse(data);
  console.log(json);
} catch (err) {
  console.error(err);
}

CodePudding user response:

If I do your task, I'll save data on a table, then I'll paste data to a json file and I'll read the file like your code.

I do that because I want to control the format of the JSON file. If you save a manual file in JSON, there are many ways you have problems with formatting JSON.

I hope my answer is helpful. Good luck!

 

  • Related