Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

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

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

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.

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

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.
like image 758
javabeangrinder Avatar asked Nov 10 '12 15:11

javabeangrinder


1 Answers

Try 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)

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

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
like image 125
georg Avatar answered Oct 11 '22 23:10

georg