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.
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.
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.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With