Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert result table to JSON array in MySQL

I'd like to convert result table to JSON array in MySQL using preferably only plain MySQL commands. For example with query

SELECT name, phone FROM person;  | name | phone | | Jack | 12345 | | John | 23455 | 

the expected JSON output would be

[   {     "name": "Jack",     "phone": 12345   },   {     "name": "John",     "phone": 23455   } ] 

Is there way to do that in plain MySQL?

EDIT:

There are some answers how to do this with e.g. MySQL and PHP, but I couldn't find pure MySQL solution.

like image 361
ronkot Avatar asked Jan 20 '17 08:01

ronkot


People also ask

How will you get data in JSON format in MySQL query?

Exporting MySQL data to JSON using the CONCAT() and GROUP_CONCAT() functions. Using a combination of CONCAT() and GROUP_CONCAT() functions, data from SQL string can be converted into JSON format. More about the usage of INTO OUTFILE can be found in the How to export MySQL data to CSV article.

Does MySQL return JSON?

MySQL supports a native JSON data type defined by RFC 7159 that enables efficient access to data in JSON (JavaScript Object Notation) documents. The JSON data type provides these advantages over storing JSON-format strings in a string column: Automatic validation of JSON documents stored in JSON columns.


2 Answers

New solution:

Built using Your great comments, thanks!

SELECT JSON_ARRAYAGG(JSON_OBJECT('name', name, 'phone', phone)) from Person; 

Old solution:

With help from @Schwern I managed to put up this query, which seems to work!

SELECT CONCAT(     '[',      GROUP_CONCAT(JSON_OBJECT('name', name, 'phone', phone)),     ']' )  FROM person; 
like image 166
ronkot Avatar answered Sep 18 '22 21:09

ronkot


You can use json_object to get rows as JSON objects.

SELECT json_object('name', name, 'phone', phone) FROM person; 

This won't put them in an array, or put commas between them. You'll have to do that in the code which is fetching them.

like image 40
Schwern Avatar answered Sep 18 '22 21:09

Schwern