JS read json file and use as an object

余生长醉 提交于 2020-08-07 07:10:11

问题


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)


回答1:


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);


来源:https://stackoverflow.com/questions/34789321/js-read-json-file-and-use-as-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!