0

I've got a var which takes a string returned by the Facebook API and turns it into a JSON object. Inside the object there is a title of Fan Pages.

var myJSON = JSON.parse('<?php echo $jsonString; ?>'); 

The part of string returned by FB of concern looks something like this:

{"data":[
    {"category":"Website",
    "name":"Page's Title",
    "access_token":"TOKEN"}
]}

I'm wrapping the <?php echo $jsonString; ?> in single quotes because if I used double quotes they'd clash with the double quotes inside the string returned by FB. However see the single quote inside Page's Title? If it happens that FB returns a string that contains a single quote that breaks my JS code and I get the Uncaught SyntaxError: Unexpected identifier in my console.

How can I make my code robust enough to parse the string while allowing for the double quotes inside it and the possibility of single quotes also?

2 Answers 2

1

you can use addslashes(), Returns a string with backslashes before characters that need to be quoted. These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).

var myJSON = JSON.parse('<?php echo addslashes($jsonString); ?>'); 
Sign up to request clarification or add additional context in comments.

Comments

1

Use addslashes()

This will return a string with backslashes before characters that need to be quoted.

var myJSON = JSON.parse('<?php echo addslashes($jsonString); ?>');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.