Sylvain
Sylvain

Reputation: 417

escape with JSON.parse()

I'm trying to apply a simple escaping process in javascript <-> php communication. I doesn't work... I'm not sure why.

here is some test code I wrote :

<head>
    <meta charset='utf-8'>
    <title>Test</title>
</head>

<body>
    <script>
        JSON.parse('[{"id":"43","english":"ar\"m","korean":"\ud314","date":"49 minute(s) ago."}]');
    </script>
</body>

</html>

The escaped character is a double quote inside the word arm. The error returned when opening the page is :

VM84:1 Uncaught SyntaxError: Unexpected token m in JSON at position 26
     at JSON.parse (<anonymous>)
    at test.html:11
(anonymous) @ test.html:11

Upvotes: 3

Views: 7690

Answers (1)

Pointy
Pointy

Reputation: 413712

When you include a JSON string as a string in JavaScript, you have to double the backslashes, because backslash is a metacharacter in both the JavaScript and the JSON syntaxes.

    JSON.parse('[{"id":"43","english":"ar\\\"m","korean":"\\ud314","date":"49 minute(s) ago."}]');

For the \" it's necessary to use three \ characters, so that when the JSON parser sees it you have \".

Note that it is not necessary to have those extra \ in the actual JSON that your server sends to the client (or that the client sends to the server).

Note that there are not too many good reasons for JSON text to be embedded in JavaScript source code as a JavaScript string constant. If you're building the JavaScript source as part of an HTML document using a server-side tool like PHP (or pretty much anything), JSON can be dropped into JavaScript source as an ordinary JavaScript object initializer, without an extra layer of quotes to make it look like a JavaScript string constant.

Upvotes: 6

Related Questions