[英]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.