per*_*lis 3 javascript php jquery json escaping
我有以下PHP代码:
$foo = new stdClass();
$foo->test='hello world';
$bar = new stdClass();
$bar->foo = json_encode($foo);
$encoded_string = json_encode($bar);
Run Code Online (Sandbox Code Playgroud)
该$encoded_string包含:
{"foo":"{\"test\":\"hello world\"}"}
Run Code Online (Sandbox Code Playgroud)
我想从javascript解析此字符串($.parseJSON例如使用jQuery ):
var data = $.parseJSON('{"foo":"{\"test\":\"hello world\"}"}');
console.log(data);
Run Code Online (Sandbox Code Playgroud)
我希望记录以下内容:
Object {foo: '{"test":"hello world"}'}
Run Code Online (Sandbox Code Playgroud)
但是Unexpected token t运行它时出现错误(使用铬)
如何在Javascript中解析此json字符串?如果有人想尝试,这是一个小提琴。
你正在运行到的问题是,输出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"}'
Run Code Online (Sandbox Code Playgroud)
如果您想从字符串值中不必要地解析JSON输出,则只需要对double编码即可$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
Run Code Online (Sandbox Code Playgroud)
当然,您应该避免使用服务器端语言来生成JavaScript代码,而应将数据设置为可通过AJAX请求的data-*属性或JSON源。
从服务器(或从属性)请求数据时,它将作为正确转义的JavaScript字符串,这是JSON.parse解析对象所必需的。