【发布时间】:2017-02-09 05:35:46
【问题描述】:
我正在尝试将读取的对象数组解析为文件中的 json 数据以循环遍历它。
Out.json文件内容
[ { id: 10,
name: 'ProspectJourney',
details:
{ name: 'ProspectJourney',
created_at: 1482943640422,
versioning: null },
m_id: 1,
monit: { memory: 192741376, cpu: 0 } },
{ id: 10904,
name: 'Servicing',
details:
{ name: 'Servicing',
created_at: 1482943651962,
versioning: null },
m_id: 2,
monit: { memory: 186843136, cpu: 0 } } ]
虽然我能够将缓冲区转换为字符串并将其注销。
const fs = require('fs');
const dataPromise = new Promise(function (resolve, reject) {
fs.readFile('Out.json', function(err, data) {
if (err)
reject(err);
else
resolve(data);
})
})
dataPromise.then((result) => {
console.log(result.toString());
})
如果我尝试解析它,则不会发生同样的情况。你能告诉我我哪里出错了
不工作
dataPromise.then((result) => {
console.log(JSON.parse(result.toString()));
})
Nodejs 版本 4.3.1
请不要建议使用任何 npm 模块
【问题讨论】:
-
该文件不包含有效的 JSON,因此您无法将其解析为 JSON。在 JSON 中,键必须用引号引起来,并且只有双引号才有效表示字符串。 json.org/example.html.
-
同时粘贴记录的数据。
-
尽量使用
require('Out.json')来避免fs -
@FelixKling 谢谢,我弄错了,出了什么问题.. 非常感谢.. :)
-
@RaR .. 当然:)
标签: javascript json node.js