我想最好只使用简单的 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;
这篇关于如何在 MySQL 中将结果表转换为 JSON 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!