【问题标题】:Parsing faulty JSON and be able to display where the error is解析错误的 JSON 并能够显示错误的位置
【发布时间】: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


【解决方案1】:

试试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是一个node项目,但也可以在web中使用:直接抢https://github.com/zaach/jsonlint/blob/master/web/jsonlint.js

正如@eh9 所建议的,围绕标准 json 解析器创建一个包装器以提供详细的异常信息是有意义的:

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

【讨论】:

    【解决方案2】:

    JSON.parse() 的内置版本没有一致的行为。当论证结构良好时它是一致的,如果不是则不一致。这可以追溯到原始 JSON 库实现中此函数的不完整规范。该规范不完整,因为它没有为异常对象定义接口。而这种情况直接引出了你的问题。

    虽然我目前不知道有现成的解决方案,但该解决方案需要编写 JSON 解析器并跟踪位置信息以进行错误处理。这可以通过以下方式无缝插入到您现有的代码中:(1)首先调用本机版本,以及(2)如果本机版本抛出异常,调用位置感知版本(它会更慢)让它抛出异常你自己的代码标准化了。

    【讨论】:

      【解决方案3】:

      如果您使用的是 NodeJS,clarinet 是一个非常好的基于事件的 JSON 解析器,它将帮助您生成更好的错误消息(行和列或错误)。 我使用clarinet's parser 构建了一个小型实用程序,它返回:

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-30
        • 1970-01-01
        • 1970-01-01
        • 2010-10-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多