2
votes

Alright, I know i’m probably going to get yelled at for asking such a ‘simple’ question (seems to be the trend around here) but check it out…

I am building a JSON parser and got everything working correctly except the parsers ability to deal with special characters. I am trying to implement the same special characters that are listed on http://www.json.org/ namely, [", \, /, b, f, n, r, t, u].

When I run these special characters through the builtin JSON.parse method though, most of them either return an error or don’t do anything at all

JSON.parse('["\\"]')
SyntaxError: Unexpected end of input

JSON.parse("['\"']")
SyntaxError: Unexpected token ‘

JSON.parse('["\b"]')
SyntaxError: Unexpected token 

JSON.parse('["\f"]')
SyntaxError: Unexpected token 

Yes, I see the other post "Parsing JSON with special characters", it has nothing to do with my question. Don't refer me to another question, I have seen them all. How does parsing special characters in JSON work?

2
The backslash codes are being interpreted by javascript. If you want to pass a backslash in a string, you need to escape it. So for JSON.parse to "see" \n, for example, you'd need JSON-parse('["\\n"]') - rici

2 Answers

1
votes

JSON.parse expects JavaScript strings.

JavaScript string literals use backslashes for escaping.

JSON uses backslashes for escaping.

So...

JSON.parse('["\\\\"]')
// ["\"]

JSON.parse("['\"']")
// SyntaxError: Unexpected token '
// JSON doesn't have single quotes as string delimiters!

JSON.parse('["\\b"]')
// [""]

JSON.parse('["\\f"]')
// [""]

JSON.parse('["\\\\b"]')
// ["\b"]

JSON.parse('["\\\\f"]')
// ["\f"]
1
votes

The reason you've got an issue here is because \ is also a marker for special characters within javascript strings.

Take your first example: '["\\"]'. As javascript parses this string, \\ is escaped to a single \ in your string, so the value passed to JSON.parse method is actually ["\"] - hence the "unexpected end of input error".

Essentially, you need to cater for the javascript parser by doubling-up on the backslash escape sequences. In this case, to pass your intended ["\\"] value to JSON.parse, you need to use JSON.parse('["\\\\"]') in javascript as that will pass the string ["\\"] into the JSON.parse method.