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
Release: 2024-11-30 01:45:18
Original
693 people have browsed it

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 |
Copy after login

The desired JSON output would resemble:

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

Modern Solution:

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

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

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;
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template