javascript 解析错误的 JSON 并能够显示错误所在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13323356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:26:06  来源:igfitidea点击:

Parsing faulty JSON and be able to display where the error is

javascriptjsonnode.jsvalidationerror-handling

提问by javabeangrinder

This is not about how to manage or correct a faulty JSON, it is about how to explain to the user where the error is in the faulty JSON.

这不是关于如何管理或更正错误的 JSON,而是关于如何向用户解释错误在错误的 JSON 中的位置。

Is there a way to find out at which position in the JSON the parser failed.

有没有办法找出解析器在 JSON 中的哪个位置失败。

I want to solve this problem in a node.js application so please keep your answers in that domain if possible.

我想在 node.js 应用程序中解决这个问题,所以如果可能的话,请把你的答案保留在那个域中。

When I use the built in JSON object and the parse method for a faulty JSON I only get the exception message SyntaxError: Unexpected string. I would like to find out where the error occurred.

当我使用内置 JSON 对象和错误 JSON 的解析方法时,我只收到异常消息SyntaxError: Unexpected string。我想找出错误发生的位置。

Preferred would be a JSON.validate(json)that returned result ok/error and the error position. Something like this:

首选将是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 wanted outcome of the above would be:

上述的想要的结果是:

The validator found a 'SyntaxError' of type 'Unexpected string' in your JSON near position 35.

回答by georg

Try jsonLint:

试试jsonLint

var faultyJsonToParse = '{"string":"value", "boolean": true"}';

try {
    jsonlint.parse(faultyJsonToParse)
} catch(e) {
    document.write('<pre>' + e)
}

result:

结果:

Error: Parse error on line 1:
...ue", "boolean": true"}
-----------------------^
Expecting 'EOF', '}', ',', ']', got 'undefined'

(although jsonLint is a node project, it can also be used in web: simply grab https://github.com/zaach/jsonlint/blob/master/web/jsonlint.js)

(虽然 jsonLint 是一个 node 项目,但它也可以在 web 中使用:只需抓取https://github.com/zaach/jsonlint/blob/master/web/jsonlint.js

As @eh9 suggested, it makes sense to create a wrapper around the standard json parser to provide detailed exception info:

正如@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

回答by eh9

The built-in versions of JSON.parse()don't have consistent behavior. It's consistent when the argument is well-formed, and inconsistent if it's not. This goes back to an incomplete specification of this function in the original JSON library implementation. The specification was incomplete because it did not define an interface for exception objects. And this situation leads directly to your question.

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

While I don't know of a solution that's off-the-shelf at this time, the solution requires writing a JSON parser and tracking position information for error handling. This can be inserted seamlessly into your existing code by (1) first invoking the native version, and (2) if the native version throws an exception, invoke the position-aware version (it'll be slower) let it throw the exception that your own code standardizes on.

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

回答by david_p

If you are using NodeJS, clarinet is a very nice event-based JSON parser that will help you generate better error messages (line and column or the error). I have build a small utility using clarinet's parserthat returns:

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

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

The code is here: https://gist.github.com/davidrapin/93eec270153d90581097

代码在这里:https: //gist.github.com/davidrapin/93eec270153d90581097