27

I'm trying so get the number of items in the array inside this piece

JSON

{
  "collection" : [
    {
      "item": "apple"
    },
    {
      "item": "banana"
    }]
}

Using the following JS (NodeJS): Updated with answers from user 'elssar'

var data = JSON.parse(fs.readFileSync(filePath));
console.log(data.collection.length);

Expected result: 2

Without specifying the encoding data will be a buffer instead of string (thanks to user nils). JSON.parse should work for both. Now I'm getting an error Unexpected token ? at Object.parse (native). Any idea how to fix this? (using Node 5.2.0)

3

1 Answer 1

27

You need to parse the content of the file to JSON.

fs.readFile(filePath, function (error, content) {
    var data = JSON.parse(content);
    console.log(data.collection.length);
});

Or

var data = JSON.parse(fs.readFileSync(filePath));

Alternatively, you could just require json files (the file extension needs to be .json)

var data = require(filePath);
console.log(data.collection.length);
Sign up to request clarification or add additional context in comments.

14 Comments

Your first snippet will probably not work, as data is undefined, and even if you used content, it would be a buffer.
@nils oops. fixed :)
Spotted that as well. Still it doesn't work for me. It still says that data is undefined. The alternative you gave me seems to work. But why is my Intelli saying it IS an built-in function but also states: use of an implicitly declared global variable 'require' ??
You still haven't set an encoding... look at my duplicate link.
@nils not required. JSON.parse works without setting the encoding
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.