Skip to content
Advertisement

SQL query JSON of MySQL 8.0 comes String instead of Array

I create a table in MySQL 8.0 as follows:

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;

It contains JSON type data, and I insert some data as:

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

And I use php to visit the database, I wish to get value of “airline” as an Array.

<?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();

?>

But it comes out a String, NOT an Array! This really annoys me, and JSON in MySQL is hard to understand.

Advertisement

Answer

Have you considered decoding JSON?

$json = json_decode('{"data": [{"city": "Houston", "state": "TX"}, {"city": "Los Angles", "state": "CA"}], "airline": ["UA", "AA"]}');

// for your case it will be :
// $json = json_decode($row['airline']);
echo var_dump($json->airline);
/**
 * array(2) {
  [0]=>
  string(2) "UA"
  [1]=>
  string(2) "AA"
}

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement