[英]Javascript decode JSON string which contains an encoded string
我有以下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"}'}
但是在運行它時會出現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"}'
如果你想從字符串值中不必要地解析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-*
屬性或可以使用AJAX請求的JSON源。
當從服務器(或從屬性)請求數據時,它將作為正確轉義的JavaScript字符串,這是解析對象所需的JSON.parse
。
你的代碼應該是
$foo = new stdClass();
$foo->test='hello world';
$bar = new stdClass();
$bar->foo = $foo;
$encoded_string = json_encode($bar);
只是json在最后編碼一次,在另一端開始解碼一次。
至於jsfiddle,你不會考慮字符串文字在它們成為“javascript內存中的字符串”之前經過額外的解碼層。
在這種情況下設置字符串文字的正確方法是(JS-JSON-JSON):
data = $.parseJSON('{"foo":"{\\\"test\\\":\\\"hello world\\\"}"}');
console.log($.parseJSON(data.foo));
簡單地顛倒你所做的編碼步驟。 http://jsfiddle.net/Jmjjp/2/
問題是雙重編碼為JSON。 如果需要將數據保留為字符串,則需要所需的解決方案
$bar->foo = addslashes(json_encode($foo));
代碼返回它應該返回的內容。
當json_encodein $ bar時,$ bar-> foo是一個字符串。 轉義此字符串以生成正確的輸出。
$bar->foo = json_encode($foo);
應該是$bar->foo = $foo
你需要逃避保護內部引號的斜線:
JSON.parse('{"foo":"{\\"test\\":\\"hello world\\"}"}');
// == Object {foo: '{"test":"hello world"}'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.