0

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...

1
  • Kindly post your JSON input. It seems String replace method is affecting the structure of your JSON. Commented Mar 29, 2019 at 12:39

1 Answer 1

1

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");

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this did the trick after also correctly escaping the unicode escape character.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.