I have JSON data passed by PHP and I need to parse it in Javascript.
item = JSON.parse('<?=json_encode($item_localized);?>');
Some trouble. I have string in $item_localized which contains single quote. Jsonlint says it valid json. Because I use '<?=json_encode($item_localized);?>'
- I receive message Uncaught SyntaxError: Unexpected identifier. I cannot use double quotes. I tried replace single quotes with \\' but it's not working.
json_encode
will generate a JSON text.
JSON.parse
needs to receive a string containing a JSON text.
You do need to quote the string, but you can't simply place '
around it because that won't escape any characters in the string that have special meaning in a string literal (like other '
characters).
If you put a string into json_encode
then you will get out a JSON text consisting of a string representation of another JSON text. Since JSON is a JS subjet, that string will be JS safe:
item = JSON.parse(<?php echo json_encode(json_encode($item_localized)); ?>);
This is, however, silly. Since JSON is a subset of JavaScript, you can just use it directly as a JavaScript literal.
item = <?php echo json_encode($item_localized); ?>;
What about item = <?=json_encode($item_localized);?>;
?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.