parsing错误的JSON并能够显示错误的位置
这不是关于如何pipe理或纠正有问题的JSON,而是关于如何向用户解释错误在哪里出错的JSON。
有没有办法找出parsing器失败的JSON中的哪个位置。
我想在node.js应用程序中解决这个问题,所以如果可能的话请保留你的答案。
当我使用内置的JSON对象和错误的JSON的parsing方法时,我只能得到exception消息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.
试试jsonLint :
var faultyJsonToParse = '{"string":"value", "boolean": true"}'; try { jsonlint.parse(faultyJsonToParse) } catch(e) { document.write('<pre>' + e) }
结果:
Error: Parse error on line 1: ...ue", "boolean": true"} -----------------------^ Expecting 'EOF', '}', ',', ']', got 'undefined'
(虽然jsonLint是一个节点项目,但也可以在web中使用:只需抓取https://github.com/zaach/jsonlint/blob/master/web/jsonlint.js )
正如@ eh9所build议的那样,在标准的jsonparsing器中创build一个包装来提供详细的exception信息是很有意义的:
JSON._parse = JSON.parse JSON.parse = function (json) { try { return JSON._parse(json) } catch(e) { jsonlint.parse(json) } } JSON.parse(someJson) // either a valid object, or an meaningful exception
JSON.parse()
的内置版本没有一致的行为。 当论证是完整的时候是一致的,否则就是不一致的。 这可以追溯到原始JSON库实现中这个函数的不完整规范。 该规范是不完整的,因为它没有定义exception对象的接口。 这种情况直接导致你的问题。
虽然目前我还不知道现成的解决scheme,但解决scheme需要编写JSONparsing器并跟踪error handling的位置信息。 (1)首先调用本地版本,然后(2)如果本地版本引发exception,则调用位置感知版本(它会更慢),让它抛出exception你自己的代码标准化。
如果您使用NodeJS,单簧pipe是一个非常好的基于事件的JSONparsing器,它将帮助您生成更好的错误消息(行和列或错误)。 我使用单簧pipe的分析器build立一个小工具,返回:
snippet (string): the actual line where the error happened line (number) : the line number of the error column (number) : the column number of the error message (string): the parser's error message
代码在这里: https : //gist.github.com/davidrapin/93eec270153d90581097