I'm sending JSON via a socket connection and would like to check if the JSON received is complete. If I try parsing incomplete JSON I do get a SyntaxError: Unexpected end of JSON input
but I don't know how to check for just that Error.
CodePudding user response:
The straigh forward way would be using try ... catch
and checking name
and message
of the exception. Of course there may be different messages for different error scenarios, but if you only need that specific error, this should work:
console.log("Incomplete JSON string");
try {
var x = JSON.parse(`{ "a": `);
} catch (e) {
if (e.name === "SyntaxError" && e.message === "Unexpected end of JSON input") {
console.log("incomplete json");
} else {
console.log(e.name, e.message);
}
}
console.log("\nInvalid JSON synax");
try {
var x = JSON.parse(`{ "a":, `);
} catch (e) {
if (e.name === "SyntaxError" && e.message === "Unexpected end of JSON input") {
console.log("incomplete json");
} else {
console.log(e.name, e.message);
}
}
But be aware, that the JSON parser only throws the first error it encounters. Ie, if it finds some invalid syntax within the JSON string, it will never throw an "Unexpected end of JSON input"
even if the string is indeed incomplete, as can be seen in the second example