如何在 MySQL 中将结果表转换为 JSON 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41758870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert result table to JSON array in MySQL
提问by ronkot
I'd like to convert result table to JSON array in MySQL using preferably only plain MySQL commands. For example with query
我想最好只使用普通的 MySQL 命令将结果表转换为 MySQL 中的 JSON 数组。例如查询
SELECT name, phone FROM person;
| name | phone |
| Hyman | 12345 |
| John | 23455 |
the expected JSON output would be
预期的 JSON 输出将是
[
{
"name": "Hyman",
"phone": 12345
},
{
"name": "John",
"phone": 23455
}
]
Is there way to do that in plain MySQL?
有没有办法在普通的 MySQL 中做到这一点?
EDIT:
编辑:
There are some answers how to do this with e.g. MySQL and PHP, but I couldn't find pure MySQL solution.
有一些答案如何使用例如MySQL 和 PHP来做到这一点,但我找不到纯 MySQL 解决方案。
回答by ronkot
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!
在@Schwern 的帮助下,我设法提出了这个查询,这似乎有效!
SELECT CONCAT(
'[',
GROUP_CONCAT(JSON_OBJECT('name', name, 'phone', phone)),
']'
)
FROM person;
回答by Schwern
You can use json_objectto get rows as JSON objects.
您可以使用json_object将行作为 JSON 对象获取。
SELECT json_object('name', name, 'phone', phone)
FROM person;
This won't put them in an array, or put commas between them. You'll have to do that in the code which is fetching them.
这不会将它们放入数组中,也不会在它们之间放置逗号。您必须在获取它们的代码中执行此操作。
回答by mikeryder
There are two "group by" functions for JSON called json_arrayagg, json_objectagg.
JSON 有两个“分组依据”函数,称为 json_arrayagg 和 json_objectagg。
This problem can be solved with:
这个问题可以通过以下方式解决:
SELECT json_arrayagg(
json_merge(
json_object('name', name),
json_object('phone', phone)
)
) FROM person;
SELECT json_arrayagg(
json_merge(
json_object('name', name),
json_object('phone', phone)
)
) FROM person;
This requires MySQL 5.7+.
这需要 MySQL 5.7+。