Home > Database > Mysql Tutorial > How to Convert a MySQL Result Table to a JSON Array Using Only Built-in Functions?

How to Convert a MySQL Result Table to a JSON Array Using Only Built-in Functions?

Patricia Arquette
Release: 2024-12-05 16:10:15
Original
803 people have browsed it

How to Convert a MySQL Result Table to a JSON Array Using Only Built-in Functions?

Converting Result Table to JSON Array in MySQL with Plain Commands

You aim to transform the result table of a MySQL query into a JSON array without external dependencies. To achieve this, MySQL provides several functions that can assist you.

New Solution

By leveraging the power of JSON_ARRAYAGG() and JSON_OBJECT() functions, you can directly aggregate individual JSON objects for each row and group them into a single JSON array.

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

Old Solution

Alternatively, you can use a combination of CONCAT() and GROUP_CONCAT() functions to construct the JSON array.

SELECT CONCAT(
    '[',
    GROUP_CONCAT(JSON_OBJECT('name', name, 'phone', phone)),
    ']'
)
FROM Person;
Copy after login

Both approaches effectively convert the result table into a valid JSON array that can be easily consumed by external applications or further processed within MySQL itself.

The above is the detailed content of How to Convert a MySQL Result Table to a JSON Array Using Only Built-in Functions?. 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