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.
Try jsonLint:
result:
(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: