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.
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.
[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' }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With