How does MySQL parse a JSON array into a string?

In MySQL, you can convert a JSON array to a string using the JSON_ARRAYAGG function.

For example, let’s say there is a table named users that contains the following data:

+----+-------+
| id | name  |
+----+-------+
| 1  | John  |
| 2  | Jane  |
| 3  | Alice |
+----+-------+

To parse these data into a JSON array and convert it into a string, you can use the following query:

SELECT JSON_ARRAYAGG(JSON_OBJECT('id', id, 'name', name)) AS json_string
FROM users;

After executing the above query, the following results will be returned:

+-------------------------------------------------------------------+
| json_string                                                       |
+-------------------------------------------------------------------+
| [{"id": 1, "name": "John"}, {"id": 2, "name": "Jane"}, {"id": 3, "name": "Alice"}] |
+-------------------------------------------------------------------+

Using JSON_ARRAYAGG, the entire result set is converted into a JSON array and returned as a string. Each row of data is transformed into a JSON object with properties for id and name.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds