简体   繁体   English

JSON解析和单引号

[英]JSON parse and single quote

I have JSON data passed by PHP and I need to parse it in Javascript. 我有PHP传递的JSON数据,我需要用Javascript解析它。

item = JSON.parse('<?=json_encode($item_localized);?>');

Some trouble. 麻烦了 I have string in $item_localized which contains single quote. 我在$ item_localized中有一个包含单引号的字符串。 Jsonlint says it valid json. Jsonlint说它是有效的json。 Because I use '<?=json_encode($item_localized);?>' - I receive message Uncaught SyntaxError: Unexpected identifier. 因为我使用'<?=json_encode($item_localized);?>' -我收到消息Uncaught SyntaxError:意外的标识符。 I cannot use double quotes. 我不能使用双引号。 I tried replace single quotes with \\' but it's not working. 我尝试用\\'代替单引号,但是它不起作用。

json_encode will generate a JSON text. json_encode将生成JSON文本。

JSON.parse needs to receive a string containing a JSON text. JSON.parse需要接收一个包含JSON文本的字符串

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. 如果将字符串放入json_encode ,则会得到一个JSON文本,该文本由另一个JSON文本的字符串表示形式组成。 Since JSON is a JS subjet, that string will be JS safe: 由于JSON是JS子对象,因此该字符串将是JS安全的:

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. 由于JSON是JavaScript的子集,因此您可以直接将其用作JavaScript文字。

item = <?php echo json_encode($item_localized); ?>;

What about item = <?=json_encode($item_localized);?>; 那么item = <?=json_encode($item_localized);?>; ?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM