【问题标题】:php json_encode() adds quotes to json retrieved from mysqlphp json_encode() 为从 mysql 检索到的 json 添加引号
【发布时间】:2016-04-26 10:58:58
【问题描述】:

我有一个包含几列的 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...] (...REST OF 输出...) }"}

当我删除大括号周围的粗体引号时,JSON.parse() JavaScript 正确地将此嵌套值视为对象而不是字符串。

我的问题是,如何从 mySQL 中检索所述 JSON 列,然后在 PHP 中回显它,这样我就不必在 PHP 中再次对其进行编码 - 这会在大括号周围添加所述引号。

【问题讨论】:

    标签: javascript php mysql json ajax


    【解决方案1】:

    如果您已经在 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);
    

    【讨论】:

      【解决方案2】:

      您需要在对其进行 json_encoding 之前解析 JSON:

      while ( $row = $result->fetch_object() ) {
           $row->detailed = json_decode($row->detailed);
           $rows[] = $row;
      }
      

      【讨论】:

      • JSON.parse 这是javascript函数,你在php中。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-13
      相关资源
      最近更新 更多