1

With JSON.parse:

This works:

JSON.parse('{\"V\":\"\u008c\"}') // => { V: '' }

This doesn't:

JSON.parse('{\"V\":\"\u0000\"}') // >> SyntaxError: Unexpected token   in JSON at position 6

What is the concept here?

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
Confused
  • 617
  • 1
  • 9
  • 17

2 Answers2

3

You can find some information in the RFC 4627. For example:

2.5. Strings

The representation of strings is similar to conventions used in the C family of programming languages. A string begins and ends with quotation marks. All Unicode characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F).

Now, related to your problem, you just need to escape the \ on your unicode character for the parsing to work:

JSON.parse('{"V":"\\u0000"}')

Result: {V: "�"}

And just for you information, no need to escape the " inside a single-quoted string in javascript.

Derlin
  • 9,572
  • 2
  • 32
  • 53
1

The only issue is that you're expressing your JSON as a Javascript string literal. This is valid JSON:

{"V":"\u0000"}

This however is a Javascript string containing the value {"V":"<NUL>"}:

'{\"V\":\"\u0000\"}'

Javascript was already interpreting the \u0000 escape sequence and JSON.parse was consequently trying to parse a JSON string with a NUL byte in it, which is illegal (NUL must be escaped).

The actual Javascript string literal representation of the JSON you were attempting is:

JSON.parse('{"V":"\\u0000"}')
                  ↑
deceze
  • 510,633
  • 85
  • 743
  • 889