Reputation: 3
I have a backend that's sending invalid JSON strings. It escapes vertical tabs as \v which is not valid in JSON and ends up being rejected by the parser.
I am trying to remedy the problem in the frontend JSON decoder:
function fromJson(json) {
if(typeof json === "string") {
var jsonString = json.replace(/\v/g, "\u000B");
return JSON.parse(jsonString)
}
else {
return json
}
}
Expected output: new string with all instances of \v replaced with the unicode line tabulation.
Actual output:
JSON.parse: SyntaxError: Unexpected token v in JSON at position...
Upvotes: 0
Views: 393
Reputation: 11414
Javascript interprets \
characters as special characters in regular expressions. It expects the character after the \
to have a special meaning, but v
isn't one of the special characters. Hence the exception Unexpected token v in JSON
.
To fix your issue you need to escape the \
character in your regex with another \
, e.g. json.replace(/\\v/g, "\u000B");
Upvotes: 1