Home >Database >Mysql Tutorial >How Can I Convert a MySQL Result Table into a JSON Array Using SQL?

How Can I Convert a MySQL Result Table into a JSON Array Using SQL?

Barbara Streisand
Barbara StreisandOriginal
2024-11-30 01:45:18746browse

How Can I Convert a MySQL Result Table into a JSON Array Using SQL?

Creating JSON Arrays from Result Tables in MySQL

Consider the task of converting a result table into a JSON array using solely MySQL commands. For instance, given a table with the columns "name" and "phone":

| name | phone |
| Jack | 12345 |
| John | 23455 |

The desired JSON output would resemble:

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

Modern Solution:

Utilizing the JSON_ARRAYAGG() function, the following query accomplishes this conversion:

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

Legacy Solution:

Employing the GROUP_CONCAT() and JSON_OBJECT() functions, this query generates the JSON array:

SELECT CONCAT(
    '[', 
    GROUP_CONCAT(JSON_OBJECT('name', name, 'phone', phone)),
    ']'
) 
FROM person;

The above is the detailed content of How Can I Convert a MySQL Result Table into a JSON Array Using SQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn