我应该如何使用Node.js解析JSON ?是否有一些模块可以安全地验证和解析JSON ?
当前回答
JSON.parse("your string");
这是所有。
其他回答
您可以简单地使用JSON.parse。
JSON对象的定义是ECMAScript 5规范的一部分。node.js基于谷歌Chrome V8引擎,符合ECMA标准。因此,node.js也有一个全局对象JSON[docs]。
注- JSON。Parse会占用当前线程,因为它是一个同步方法。因此,如果您计划解析大型JSON对象,请使用流式JSON解析器。
利用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对象:
JSON.parse(str);
只是为了让这个问题尽可能复杂,并引入尽可能多的包……
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服务器可以处理其他请求。
为了安全起见,用这个吧
var data = JSON.parse(Buffer.concat(arr).toString());
推荐文章
- 使用Python将XML转换为JSON ?
- 当你双击日文文本时,Chrome如何决定突出显示什么?
- npm install和npm run build有什么区别?
- 使用async/await尝试/捕获块
- 为什么.json()返回一个承诺?
- 更改mocha的默认超时时间
- 如何设置一个iframe src属性从一个变量在AngularJS
- 解析日期没有时区javascript
- 是否有一种方法可以检查数据属性是否存在?
- Chrome不会删除会话cookie
- 如何在JavaScript中获得UTC时间戳?
- 如何使用jQuery等待CSS3过渡结束?
- 在Chrome和Firefox中用Javascript报告的神秘的“脚本错误”
- 设置CSS属性在JavaScript?
- 右击是Javascript事件吗?