douoyou3348 2017-02-21 05:42
浏览 68
已采纳

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

The problem is simple to understand and demonstrate.

This code works fine:

<?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>

This code does not:

<?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>

Outputs error in console: Uncaught SyntaxError: missing ) after argument list - (index):20 where line 20 is one with JSON.parse and if you look at the source code of the page, the line reads:

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"]');

You may notice that the two code samples are exactly the same, the arrays even have the same length, the only difference is that the strings are longer in the second one. Does this mean there's a maximum length to the strings that can be parsed by JSON?

  • 写回答

1条回答 默认 最新

  • dream0614 2017-02-21 05:46
    关注

    Your JSON data contains '. So if you inject that data into a ' delimited string literal, that string literal will be closed prematurely and cause a syntax error. Simple example:

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

    You should notice that if you look at the generate JavaScript source.

    There is no need to use JSON.parse here. The injected JSON can be interpreted as a JavaScript object/array literal:

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

    See also: How to pass variables and data from PHP to JavaScript?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂