I'm using PHP to fetch JSON stored in a MySQL database, put it into a PHP variable, and pass it to JQuery, which writes the content to the page:
data = $.parseJSON('<?=$my_json;?>');
$.each(data.links, function(entryIndex, entry) {
//do some stuff here
});
Everything works fine when the JSON looks like this:
{
"links": [{
"url": "http://domain1.com",
"title": "Title 1",
"description": "This is an example for my question on Stack Overflow"
}, {
"url": "http://domain2.com",
"title": "Title 2",
"description": "This is another example for my question on Stack Overflow"
}, {
"url": "http://domain3.com",
"title": "Title 3",
"description": "This is a third example for my question on Stack Overflow"
}]
}
But when the JSON content includes quotes, I get an error reading "Uncaught SyntaxError: Unexpected end of JSON input," even though the quotes are escaped, like this:
{
"links": [{
"url": "http://domain1.com",
"title": "Title 1",
"description": "This is an \"example\" for my question on Stack Overflow"
}, {
"url": "http://domain2.com",
"title": "Title 2",
"description": "This is another \"example\" for my question on Stack Overflow"
}, {
"url": "http://domain3.com",
"title": "Title 3",
"description": "This is a third \"example\" for my question on Stack Overflow"
}]
}
What am I doing wrong?
data = $.parseJSON('<?=$my_json;?>');
The thing you're doing here is you're trying to wrap up the JavaScript object around quotes and passing it as a string to $.parseJSON
function.
This function only parses JSON string which is a string should be formed with JSON structure and that will then converted to a JavaScript object by the function.
While $my_json
variable already has a JavaScript object, you don't need to use $.parseJSON
function. You can just assign it to the JavaScript variable like the following one:
data = <?= $my_json ?>;
$.each(data.links, function(entryIndex, entry) {
//do some stuff here
});