如何在 MySQL 中将结果表转换为 JSON 数组

2021-11-20 00:00:00 json etl data-conversion mysql

我想最好只使用简单的 MySQL 命令将结果表转换为 MySQL 中的 JSON 数组.例如查询

SELECT name, phone FROM person;|姓名 |电话 ||杰克 |12345 ||约翰 |23455 |

预期的 JSON 输出是

<预><代码>[{"name": "杰克",电话":12345},{"name": "约翰",电话":23455}]

有没有办法在普通的 MySQL 中做到这一点?

有一些答案是如何做到这一点的,例如MySQL 和 PHP,但我找不到纯 MySQL 解决方案.

解决方案

新解决方案:

使用您的精彩评论构建,谢谢!

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

<小时>

旧解决方案:

在@Schwern 的帮助下,我设法提出了这个查询,这似乎有效!

SELECT CONCAT('[',GROUP_CONCAT(JSON_OBJECT('name', name, 'phone', phone)),']')从人;

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.

解决方案

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;

相关文章