Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJs read JSON file

I am tying to read a json file using NodeJs

my code is pretty basic,

  var obj = require("./sample.json");
  console.log(obj[0]);

The sample.json file contains a stringified JSON like this,

"[{\"sample\":\"good\",\"val\":76159}]"

However the console.log output is '[' not the first element in the variable. I have tried opening the file in the long way like this as well.

var obj;
fs.readFile('sample.json', 'utf8', function (err, data) {
  if (err) throw err;
  obj = JSON.parse(data);
  console.log(obj[0]);
});

But here also the output is '[' why is the json file not properly parsed? How can I fix it?

Thanks in advance.

like image 909
rksh Avatar asked Apr 27 '26 09:04

rksh


2 Answers

Your file should contain:

[{"sample":"good","val":76159}]

If it contains

"[{\"sample\":\"good\",\"val\":76159}]"

Then it is encoded twice. It is still valid JSON because it is a string, but this JSON does not represent the JavaScript Object:

[{
  sample:"good",
  val:76159
}]

But a string with the content [{"sample":"good","val":76159}].

If you add a second parse (the first one is implicitly done by the require):

var obj = JSON.parse(require("./sample.json"));
console.log(obj[0]);

then you will see that the the correct information is logged.
So your initial problem is that you stored the value the wrong way in ./sample.json.

like image 142
t.niese Avatar answered Apr 28 '26 23:04

t.niese


[info.json]

[{
    "name" : "Young",
    "age" : 100,
    "skill" : "js"
}]

[main.js]

var jsonObj = require('./info.json');
console.log(jsonObj[0]);

[result]

{ name: 'Young', age: 100, skill: 'js' }
like image 30
Young Avatar answered Apr 28 '26 22:04

Young