【发布时间】:2012-10-30 16:12:03
【问题描述】:
这不是关于如何管理或更正错误 JSON,而是关于如何向用户解释错误在错误 JSON 中的位置。
有没有办法找出解析器在 JSON 中的哪个位置失败。
我想在 node.js 应用程序中解决此问题,因此请尽可能将您的答案保留在该域中。
当我使用内置 JSON 对象和错误 JSON 的解析方法时,我只会收到异常消息 SyntaxError: Unexpected string。我想知道错误发生在哪里。
首选返回结果 ok/error 和错误位置的JSON.validate(json)。像这样的:
var faultyJsonToParse = '{"string":"value", "boolean": true"}';
var result = JSON.validate(faultyJsonToParse);
if (result.ok == true) {
console.log('Good JSON, well done!');
} else {
console.log('The validator found a \'' + result.error + '\' of type \'' + result.errorType + '\' in your JSON near position ' + result.position);
}
以上想要的结果是:
The validator found a 'SyntaxError' of type 'Unexpected string' in your JSON near position 35.
【问题讨论】:
-
您是否希望对发生错误的缩小 JSON 字符串进行索引?
-
是的,类似的。我猜这也可能是解决大型 JSON 问题的途径。
-
是的..也许可以通读一下..bugzilla.mozilla.org/show_bug.cgi?id=507998它可能无法回答您的问题,但可能会深入了解为什么本机不存在此功能。
标签: javascript json node.js validation error-handling