3

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.

5
  • 2
    Did you try printing the data? Commented Jul 12, 2016 at 9:58
  • 1
    jsfiddle.net/xgfgmx08 if data is what you said, it should work. double check what's inside data Commented Jul 12, 2016 at 10:00
  • @BeNdErR can you try code where it opens a json in a local computer, I guess the problem is the way we open the file because the example works fine, is there an issue in the way we open the json file? Commented Jul 12, 2016 at 10:06
  • 1
    @rksh try to console.log(data) as soon as you read it. What's the output? Commented Jul 12, 2016 at 10:08
  • Have you made: var fs = require('fs'); and tested that you get data once you read the file as commented by @BeNdErR ? Commented Jul 12, 2016 at 10:24

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

4

[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' }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.