[英]php json_encode() adds quotes to json retrieved from mysql
我有一個帶有幾列的mysql表,其中之一是“詳細的”,包含json字符串-包含6個鍵。
{
"x": [
-0.02,
-0.04,
-0.05
],
"y": [
-0.01,
0,
0,
-0.01
],
"z": [
0.04,
0,
-0.03,
-0.01
],
"roll": [
0.5,
0.6,
0.6
],
"pitch": [
-3.4,
-3.3,
-3.3
],
"yaw": [
224.2,
224.2,
224.2
] }
然后在php中,我選擇三列,其中之一稱為json列。
$sql = "SELECT date, speed, detailed FROM info_table";
$result = $conn->query ( $sql );
if ($result-> num_rows ) {
while ( $row = $result->fetch_object() ) {
$rows[] = $row;
}
}
echo json_encode($rows);
在JavaScript中,我進行AJAX調用以檢索這些值,然后解析它們。
data = JSON.parse(xmlhttp.responseText);
到目前為止,到目前為止,當我嘗試進入嵌套屬性時,將返回JSON對象,但是。
data[1].detailed.x[1]
它給了我不確定的,因為“詳細”之后的所有內容都被視為字符串而不是對象。
我知道是什么原因造成的,當我回顯json_encode的結果時,在php中得到了:
{“ date”:“ 2016-04-22 14:50:24”,“ speed”:“ 0”,“ detailed”: “ {\\” x \\“:[-0.02,-0 ...](。 ..剩余輸出...)} “ }
當我刪除大括號括起來的大括號時,JSON.parse()JavaScript正確地將此嵌套值視為對象而非字符串。
我的問題是,如何從mySQL中檢索所說的JSON列,然后在PHP中回顯它,所以我不必在PHP中再次對其進行編碼-這在大括號中添加了所說的引號。
如果您已經在db中包含json,則需要先對其進行解碼,然后再對整個內容進行編碼:
$sql = "SELECT date, speed, detailed FROM info_table";
$result = $conn->query($sql);
if ($result->num_rows) {
while ($row = $result->fetch_object()) {
$row->detailed = json_decode($row->detailed);
$rows[] = $row;
}
}
echo json_encode($rows);
您需要在json_encoding之前解析JSON:
while ( $row = $result->fetch_object() ) {
$row->detailed = json_decode($row->detailed);
$rows[] = $row;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.