PHP json_encode() 将引号添加到从 MySQL 检索的 JSON 中


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]

它给了我未定义,因为"详细"之后的所有内容都被视为字符串而不是对象。

我知道是什么原因造成的,在 php 中,当我回显我得到的结果时json_encode:

{"日期":"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;
}