Py学习  »  DATABASE

MySQL 8.0的SQL查询JSON是字符串而不是数组

John • 3 年前 • 1668 次点击  

CREATE TABLE `airline_table` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`info` json DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

它包含JSON类型的数据,我插入一些数据如下:

INSERT INTO airline_table VALUES ('1','{"data": [{"city": "Houston", "state": "TX"}, 
      {"city": "Los Angles", "state": "CA"}], "airline": ["UA", "AA"]}');

我使用php访问数据库,希望得到“airline”作为数组的值。

<?php

$mysqli = new mysqli("localhost", "root", "aproot2019", "test");
$sql = "SELECT id, info -> '$.airline' AS airline FROM airline_table";

$result = $mysqli->query($sql);
$row = $result->fetch_array();
//print_r($row);
$airline = $row['airline'];

echo $airline . "<br>";   //  ["UA", "AA"] , this is a string but not an array, how can I have an Array? 
echo is_array($airline) ? 'Array' : 'not an Array'     . "<br>";      // not an Array
echo is_string($airline) ? 'String' : 'not a String'   . "<br>" ;    // String

$mysqli->close();

?>

但它是一个字符串,而不是数组! 这让我很恼火,MySQL中的JSON很难理解。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133560
文章 [ 2 ]  |  最新文章 3 年前