Why does JSON.parse choke on encoded characters in nodejs?

I'm attempting to look up the word "flower" in Google's dictionary semi-api. Source:

https://gist.github.com/DelvarWorld/0a83a42abbc1297a6687

Long story short, I'm calling JSONP with a callback paramater then regexing it out.

But it hits this snag:

undefined:1
ple","terms":[{"type":"text","text":"I stopped to buy Bridget some \x3cem\x3ef
                                                                    ^
SyntaxError: Unexpected token x
    at Object.parse (native)

Google is serving me escaped HTML characters, which is fine, but JSON.parse cannot handle them?? What's weirding me out is this works just fine:

$ node

> JSON.parse( '{"a":"\x3cem"}' )
  { a: '<em' }

I don't get why my thingle is crashing

Edit These are all nice informational repsonses, but none of them help me get rid of the stacktrace.

\xHH is not part of JSON, but is part of JavaScript. It is equivalent to \u00HH. Since the built-in JSON doesn't seem to support it and I doubt you'd want to go through the trouble of modifying a non-built-in JSON implementation, you might just want to run the code in a sandbox and collect the resulting object.

Edited by DelvarWorld:

Ding ding ding! Here's my updated example, if JSON.parse fails I attempt to return it in a new Function() body:

https://gist.github.com/DelvarWorld/256a46a0c3c5b1b196d1

According to http://json.org, a string character in a JSON representation of string may be:

  • any-Unicode-character- except-"-or--or- control-character
  • \"
  • \
  • \/
  • \b
  • \f
  • \n
  • \r
  • \t
  • \u four-hex-digits

So according to that list, the "json" you are getting is malformed at \x3

The reason why it works is because these two are equivalent.

JSON.parse( '{"a":"\x3cem"}' )

and

JSON.parse( '{"a":"<em"}' )

you string is passed to JSON.parse already decoded since its a literal \x3cem is actually <em

Now, \xxx is valid in JavaScript but not in JSON, according to http://json.org/ the only characters you can have after a \ are "\/bfnrtu.

answer is correct, but needs couple of modifications. you might wanna try this one: https://gist.github.com/Selmanh/6973863