我尝试使用下面的代码解析 JSON 文件,但出现错误:
var fs = require('fs');
var sampleData = require("./sampleData.json");
var dataInArray = JSON.parse(sampleData.toString());
这是错误:
$ node prog.js
undefined:1
[object Object]
^
SyntaxError: Unexpected token o
at Object.parse (native)
at Object.<anonymous> (~/prog.js:3:24) //The line where I perform the JSON parsing
我做错了什么?
最佳答案
当您需要带有节点的 json 时,它已经为您解析了。 就这么做
var sampleData = require("./sampleData.json");
console.log(Object.keys(sampleData));
和sampleData
将是JSON表示的对象。
参见this question .
编辑:执行此操作时请小心,因为如果您的应用中出现多个 require
,您的数据可能会被缓存并且不会重新加载。 (请参阅 node.js 文档)。
如果您在应用程序处于事件状态时更改数据,则最好使用常规 readFile
和 JSON.parse
在需要时从头开始重新加载数据。
关于javascript - 直接从 node.js 中的文件解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29164906/