什么限制了这个JSON解析,我该怎么做才能解决它?

时间:2017-02-21 05:42:59

标签: javascript php json

问题很容易理解和演示。

此代码可以正常工作:

<?php
    $title = array("dfg","sdfsdg","asfas","Sdfh","Ssdth","Csdgo");
    $title_json = json_encode($title);
?>
<script>
    var obj = JSON.parse('<?= $title_json; ?>');
    console.log(obj);
</script>

此代码不会:

<?php
    $title = array("Is President Trump still using his old Android phone?","Trump sets a dizzying WH pace in first days","Trumps White House Charm Offensive a Contrast to Solitary Obama","The inside story of a basketball teen so tall, he doesn't look real","Scientists say they are closer to making Star Wars holograms","Sperm theft lawsuit leaves appeals court weighing how much a life is worth","Call it Smunday: Heinz pushing to make Super Bowl Monday a national holiday");
    $title_json = json_encode($title);
?>
<script>
    var obj = JSON.parse('<?= $title_json; ?>');
    console.log(obj);
</script>

在控制台中输出错误:Uncaught SyntaxError: missing ) after argument list - (index):20其中第20行是带有JSON.parse的错误,如果你查看页面的源代码,该行显示为:

var obj = JSON.parse('["Is President Trump still using his old Android phone?","Trump sets a dizzying WH pace in first days","Trump's White House Charm Offensive a Contrast to Solitary Obama","The inside story of a basketball teen so tall, he doesn't look real","Scientists say they are closer to making 'Star Wars' holograms","Sperm theft lawsuit leaves appeals court weighing how much a life is worth","Call it 'Smunday': Heinz pushing to make Super Bowl Monday a national holiday"]');

您可能会注意到两个代码示例完全相同,数组甚至具有相同的长度,唯一的区别是字符串在第二个中更长。这是否意味着JSON可以解析字符串的最大长度?

1 个答案:

答案 0 :(得分:8)

您的JSON数据包含'。因此,如果将该数据注入'分隔的字符串文字,则该字符串文字将过早关闭并导致语法错误。简单的例子:

var foo = '{"key": "This key's value"}';

如果你看一下生成JavaScript源代码,你应该注意到。

此处无需使用JSON.parse。注入的JSON可以解释为JavaScript对象/数组文字:

var obj = <?= $title_json; ?>;

另请参阅:How to pass variables and data from PHP to JavaScript?