加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – Javascript解码包含编码字符串的JSON字符串

发布时间:2020-12-13 21:48:27 所属栏目:PHP教程 来源:网络整理
导读:我有以下 PHP代码: $foo = new stdClass(); $foo-test='hello world'; $bar = new stdClass(); $bar-foo = json_encode($foo); $encoded_string = json_encode($bar); $encoded_string包含: {"foo":"{"test":"hello world"}"} 我想从javascript解析这
我有以下 PHP代码:

$foo = new stdClass();
    $foo->test='hello world';
    $bar = new stdClass();
    $bar->foo = json_encode($foo);
    $encoded_string = json_encode($bar);

$encoded_string包含:

{"foo":"{"test":"hello world"}"}

我想从javascript解析这个字符串(例如使用jQuery的$.parseJSON):

var data = $.parseJSON('{"foo":"{"test":"hello world"}"}');
console.log(data);

我希望记录以下内容:

Object {foo: '{"test":"hello world"}'}

但是在运行它时会出现意外的令牌错误(使用铬)

如何在Javascript中解析这个json字符串? Here’s a fiddle,如果有人想尝试.

解决方法

您遇到的问题是json_encode的输出不能直接用作JavaScript中的字符串.

json_encode输出一个可用的JavaScript对象:

<?php
$foo = new stdClass();
$foo->test='hello world';
$bar = new stdClass();
$bar->foo = json_encode($foo);
$encoded_string = json_encode($bar);
?>
var a = <?php $encoded_string ?>;
console.log(a.foo); // produces '{"test":"hello world"}'

如果你想从字符串值中不必要地解析JSON输出,你只需要对$encoded_string进行双重编码:

<?php
$foo = new stdClass();
$foo->test='hello world';
$bar = new stdClass();
$bar->foo = json_encode($foo);
$encoded_string = json_encode(json_encode($bar));
?>
var aStr = <?php $encoded_string ?>;
var a = JSON.parse(aStr);
console.log(a.foo); //same as before

当然,您应该避免使用服务器端语言来生成JavaScript代码,而是将数据设置为data-* attribute或可以使用AJAX请求的JSON源.

当从服务器(或从属性)请求数据时,它将作为正确转义的JavaScript字符串,这是解析对象所需的JSON.parse.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读