我正在以这种方式在 javascript 中创建一个 json
jsonArr.push({
position: 'WN',
wind: windWN,
wave: waveWN,
sea: seaWN
});
var myJsonString = JSON.stringify(jsonArr);
我使用 jsonData 通过 AJAX 方法发送它:jsonData:Ext.encode(myJsonString)
当我发送它时,我的 json 数组看起来像这样:
在 PHP 方面,我获取 Json 并以这种方式对其进行解码:
$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = json_decode($rawpostdata, true);
我尝试了 print_r( $rawpostdata2[1]);
并得到了 '{' 作为“字符串”的第二个字符,我不明白为什么。
在另一边,我尝试了 print_r($rawpostdata)
,将结果剪切/粘贴到 $string 中,然后像这样重新测试我的 json_decode:
$rawpostdata = file_get_contents("php://input");
// print_r($rawpostdata);
$string = '[{"position":"N","wind":"2","wave":"65","sea":"65"},{"position":"E","wind":"3","wave":"5","sea":"6"},{"position":"S","wind":"56","wave":"4","sea":"8"},{"position":"W","wind":"1","wave":"56","sea":"84"},{"position":"NE","wind":"5","wave":"6","sea":"65"},{"position":"ES","wind":"6","wave":"45","sea":"6"},{"position":"SW","wind":"69","wave":"8","sea":"4"},{"position":"WN","wind":"7","wave":"8","sea":"56"}]';
$rawpostdata2 = json_decode($string,true);
print_r ($rawpostdata2[1]);
它给了我正确的结果!
Array ( [position] => E [wind] => 3 [wave] => 5 [sea] => 6 )
你有什么解释吗?
编辑:我通过制作另一个 json_decode 使其工作
$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = json_decode($rawpostdata,true);
$rawpostdata3 = json_decode($rawpostdata2,true);
可是我不是很懂...
最佳答案
首先,您创建 json 字符串:
var myJsonString = JSON.stringify(jsonArr);
然后将结果字符串再次编码为 json:
Ext.encode(myJsonString)
因此,您必须在 PHP 中 json_decode()
两次。
关于javascript - 奇怪的行为 json_decode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28151207/