Jasper
Jasper

Reputation: 2404

PHP JSON Parser v.s. Javascript JSON Parser

I have an array via json_encode of PHP serialize:

json_encode(array('pattern' => '^(?:/?site/(?[\w\-]+))?(?:/?intl/(?[a-z]{2}(?:\-[a-z]{2})?)/?)?(/?(?.*))'));
// output json: {"pattern":"^(?:\/?site\/(?[\\w\\-]+))?(?:\/?intl\/(?[a-z]{2}(?:\\-[a-z]{2})?)\/?)?(\/?(?.*))"}

I tried to decode in Javascript:

JSON.parse('{"pattern":"^(?:\/?site\/(?[\\w\\-]+))?(?:\/?intl\/(?[a-z]{2}(?:\\-[a-z]{2})?)\/?)?(\/?(?.*))"}');

Then I don't understand why do I get an error "Uncaught SyntaxError: Unexpected token w" ?? Is PHP and Javascript JSON parser difference?

Upvotes: 3

Views: 206

Answers (1)

Steven Moseley
Steven Moseley

Reputation: 16345

The problem is because you're using JSON.parse() and enclosing your JSON string in single quotes.

So your escaped regex string gets unescaped in the interpretation of the outer string-literal (single-quoted), and then gets mixed up in the interpretation of the value of the string pattern (double-quoted), ultimately causing JavaScript to choke trying to decipher "\w".

The following example, mimicking PHP rendering the JSON verbatim to a declaration, works fine in a JS console:

var json = {"pattern":"^(?:\/?site\/(?[\\w\\-]+))?(?:\/?intl\/(?[a-z]{2}(?:\\-[a-z]{2})?)\/?)?(\/?(?.*))"}

If you want to use JSON.parse, you have to first double-escape your JSON string in PHP

$json = json_encode(array('pattern' => '^(?:/?site/(?[\w\-]+))?(?:/?intl/(?[a-z]{2}(?:\-[a-z]{2})?)/?)?(/?(?.*))'));
$json = str_replace('\', '\\', $json);
// output json: {"pattern":"^(?:\\/?site\\/(?[\\\\w\\\\-]+))?(?:\\/?intl\\/(?[a-z]{2}(?:\\\\-[a-z]{2})?)\\/?)?(\\/?(?.*))"}

Then, in JS:

var json = JSON.parse('{"pattern":"^(?:\\/?site\\/(?[\\\\w\\\\-]+))?(?:\\/?intl\\/(?[a-z]{2}(?:\\\\-[a-z]{2})?)\\/?)?(\\/?(?.*))"}')

Upvotes: 4

Related Questions