[英]How to load JSON array from file NodeJS?
How should you load JSON array from file in NodeJS?你应该如何从 NodeJS 中的文件加载 JSON 数组?
var fs = require('fs');
fs.readFile('input.json', (err, fileContent) => {
if( err ) {
} else {
data = JSON.parse(fileContent);
console.log(fileContent);
}
})
input.json输入.json
[
{ "date": "2017-02-18" },
{ "date": "2017-02-18" },
]
Getting error: SyntaxError: Unexpected token ] in JSON at position获取错误:SyntaxError: Unexpected token ] in JSON at position
Make sure JSON is valid.确保 JSON 有效。 ie, no trailing commas.
即,没有尾随逗号。
If you are loading something like a configuration, simply const data = require('./json-file.json')
.如果您正在加载类似配置的内容,只需
const data = require('./json-file.json')
。
node can simply require json files natively. node 可以简单地在本机上要求 json 文件。 however this is synchronous.
然而这是同步的。 So only use it for something like loading a config in start-up.
所以只将它用于诸如在启动时加载配置之类的事情。
Update input.json it contains one extra comma( , ) at the end before closing bracket ( ] )更新 input.json,它在结束括号 ( ] ) 之前包含一个额外的逗号 ( , )
[
{ "date": "2017-02-18" },
{ "date": "2017-02-18" }
]
and If you are reading json file in node.js and want to show data in json then place UTF8 while reading the file并且如果您正在 node.js 中读取json文件并希望在 json 中显示数据,则在读取文件时放置UTF8
var fs = require('fs');
fs.readFile('input.json', 'utf8',(err, fileContent) => {
if( err ) {
} else {
data = JSON.parse(fileContent.toString());
console.log(fileContent);
console.log(data);
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.