jcalfee314 jcalfee314 - 3 months ago 15
JSON Question

Parsing all possible UTF-8 values in a json string

How can I get the following to run without the unexpected token error?

I would like to parse any possible utf-8 in a JSON string. Since characters like \u0000 (null) are valid UTF-8 I should be able to parse them in a json string right?

s='{"body": "\u0000"}'
JSON.parse(s)



SyntaxError: Unexpected token in JSON at position 10


I get the same error using
JSON.parse(unescape(encodeURIComponent(s)))
.

Here is a larger sample from the data set:

\u0000\u0001\u0002\u0003\u0004\u0005\u0006\a\b\t\n
!\"#$%&'()*+,-./0123456789:;<=>?
ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύ

Answer

Use double reverse solidus and it's good to go. Such as:

s=`{"body": "\\u0000"}`
JSON.parse(s)

or

s=`{"body": "\\t"}`
JSON.parse(s)