I met a very little strange problem about the return error of JSON.parse() function: I use this function to validate JSON string that i retrieve from a web based editor. That string is pre-manipulated using JSON.stringify() function. more precisely:
JSON.stringify(data, null, 4)
So, when I use Firefox (v107.0.1), in case of malformed string, I can display the line number and the column number of the typo, but when I use Chrome (v 107.0.5304.87) lines are not recognized.
I assume that is a JS engine problem but I was wondering if there is a way to fix the problem.
Thanks
- test with different browsers versions
- change string format
CodePudding user response:
Exceptions between browsers are likely implementation specific.
But if you do want a more robust JSON parser, you could use JSON5, with this line numbers etc, should be consistent between browsers.
eg..
console.log('Incorrect JSON');
//with error
try {
var a = JSON5.parse(`
{
hello: 'there'x
}`);
console.log(a);
} catch (e) {
console.log('JSON error at', e.lineNumber, e.columnNumber);
}
console.log('Valid JSON');
//corrected
try {
var a = JSON5.parse(`
{
hello: 'there'
}`);
console.log(a);
} catch (e) {
console.log('JSON error at', e.lineNumber, e.columnNumber);
}
<script src="https://unpkg.com/json5@^2.0.0/dist/index.min.js"></script>