我应该如何使用Node.js解析JSON ?是否有一些模块可以安全地验证和解析JSON ?
当前回答
这里的每个人都讲过JSON。所以我想说点别的。有一个伟大的模块连接许多中间件,使应用程序的开发更容易和更好。中间件之一是bodyParser。它可以解析JSON, html表单等。还有一个仅用于JSON解析的特定中间件noop。
看看上面的链接,它可能对你很有帮助。
其他回答
利用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流?使用JSONStream。
var request = require('request')
, JSONStream = require('JSONStream')
request({url: 'http://isaacs.couchone.com/registry/_all_docs'})
.pipe(JSONStream.parse('rows.*'))
.pipe(es.mapSync(function (data) {
return data
}))
https://github.com/dominictarr/JSONStream
只是为了让这个问题尽可能复杂,并引入尽可能多的包……
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服务器可以处理其他请求。
只是想完成答案(因为我挣扎了一段时间),想展示如何访问json信息,这个例子显示了访问json数组:
Var request = require('request'); 请求(“https://server/run?oper_get_groups_joined_by_user_id &user_id=5111298845048832',函数(错误,响应,body) { 如果(!错误&&响应。statusCode == 200) { var jsonArr = JSON.parse(body); console.log (jsonArr); console.log("group id:" + jsonArr[0].id); } })
这里的每个人都讲过JSON。所以我想说点别的。有一个伟大的模块连接许多中间件,使应用程序的开发更容易和更好。中间件之一是bodyParser。它可以解析JSON, html表单等。还有一个仅用于JSON解析的特定中间件noop。
看看上面的链接,它可能对你很有帮助。
推荐文章
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔
- 在VS Code中禁用“Comments are not allowed In JSON”错误
- TypeScript枚举对象数组
- 如何在Kotlin解析JSON ?
- 在React.js中正确的img路径
- 在React.js中更新组件onScroll的样式
- onClick ReactJS调用多个函数
- 如何在JavaScript中转义单引号(')?
- JSON文件的蒙古导入