我应该如何使用Node.js解析JSON ?是否有一些模块可以安全地验证和解析JSON ?
当前回答
我用的是fs-extra。我非常喜欢它,因为——尽管它支持回调——它也支持承诺。所以它只是让我以一种更可读的方式编写代码:
const fs = require('fs-extra');
fs.readJson("path/to/foo.json").then(obj => {
//Do dome stuff with obj
})
.catch(err => {
console.error(err);
});
它还提供了许多标准fs模块中没有的有用方法,除此之外,它还连接了来自本地fs模块的方法并对它们进行了承诺。
注意:你仍然可以使用原生Node.js方法。它们被承诺并复制到fs-extra。参见fs.read() & fs.write()的注释
所以基本上都是优势。我希望这对其他人有用。
其他回答
一定要确保使用JSON。如果你的json中有一些损坏的数据,那么使用这段代码而不是简单的json,解析try catch块作为节点总是抛出一个意外错误。解析
try{
JSON.parse(data)
}
catch(e){
throw new Error("data is corrupted")
}
只是为了让这个问题尽可能复杂,并引入尽可能多的包……
const fs = require('fs');
const bluebird = require('bluebird');
const _ = require('lodash');
const readTextFile = _.partial(bluebird.promisify(fs.readFile), _, {encoding:'utf8',flag:'r'});
const readJsonFile = filename => readTextFile(filename).then(JSON.parse);
这让你做:
var dataPromise = readJsonFile("foo.json");
dataPromise.then(console.log);
或者如果你使用async/await:
let data = await readJsonFile("foo.json");
与仅使用readFileSync相比的优点是,在从磁盘读取文件时,Node服务器可以处理其他请求。
利用Lodash的attempt函数返回一个错误对象,可以用isError函数处理。
// Returns an error object on failure
function parseJSON(jsonString) {
return _.attempt(JSON.parse.bind(null, jsonString));
}
// Example Usage
var goodJson = '{"id":123}';
var badJson = '{id:123}';
var goodResult = parseJSON(goodJson);
var badResult = parseJSON(badJson);
if (_.isError(goodResult)) {
console.log('goodResult: handle error');
} else {
console.log('goodResult: continue processing');
}
// > goodResult: continue processing
if (_.isError(badResult)) {
console.log('badResult: handle error');
} else {
console.log('badResult: continue processing');
}
// > badResult: handle error
正如这里提到的其他答案,你可能想要一个本地json文件,你知道是安全的,就像一个配置文件:
var objectFromRequire = require('path/to/my/config.json');
或者使用全局JSON对象将字符串值解析为对象:
var stringContainingJson = '\"json that is obtained from somewhere\"';
var objectFromParse = JSON.parse(stringContainingJson);
请注意,当您需要一个文件时,该文件的内容会被评估,如果它不是json文件而是js文件,则会引入安全风险。
在这里,我发布了一个演示,你可以看到这两种方法,并在线使用它们(解析示例在app.js文件中-然后点击运行按钮,在终端中看到结果): http://staging1.codefresh.io/labs/api/env/json-parse-example
您可以修改代码并查看影响…
使用JSON对象:
JSON.parse(str);
推荐文章
- 窗口。亲近与自我。close不关闭Chrome中的窗口
- 为什么PHP的json_encode函数转换UTF-8字符串为十六进制实体?
- 同步和异步编程(在node.js中)的区别是什么?
- 在d3.js中调整窗口大小时调整svg的大小
- 如何编辑通过npm安装的节点模块?
- 如何将两个字符串相加,就好像它们是数字一样?
- 绑定多个事件到一个监听器(没有JQuery)?
- Ajax会调用什么样的响应,比如'for (;;);{json data}的意思?
- 在JavaScript中将JSON字符串解析为特定对象原型
- 将字符串“true”/“false”转换为布尔值
- 如何使用JavaScript代码获得浏览器宽度?
- event.preventDefault()函数在IE中无法工作
- indexOf()和search()的区别是什么?
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误