MySQL 5.7使用新的json功能将行作为json返回 [英] mySQL 5.7 return row as json using new json features
问题描述
我正在研究一些新的 JSON功能并且想知道是否存在一种聪明(或明显)的方法来将行集作为JSON对象返回.理想情况下,无需命名键或使用任何类型的字符串操作.
I was going over some of the new JSON features and was wondering if there is a clever (or obvious) way to return a rowset as a JSON object. Ideally without having to name the keys or use any kind of string manipulation.
示例:
TABLE: people
id name age
1 bob 54
2 jay 32
3 john 10
SELECT * FROM people where id = 1
会返回
{"id":1,"name":"bob","age":54}
甚至更好
SELECT * FROM people
将返回所有3个对象的数组
would return an array of all 3 objects
如果您不熟悉新的JSON功能,则新功能之一是JSON_OBJECT
If you are not familiar with the new JSON features, one of the new functions is JSON_OBJECT
SELECT JSON_OBJECT('key1', 1, 'key2', 'abc')
将返回键值JSON对象.
would return a key value JSON object.
推荐答案
取决于您所说的给键命名或任何类型的字符串处理".如果您很乐意将上述键名和字符串操作的命名封装在存储的proc中,以使您在调用过程时无需命名键,那么可以,您可以:
Depends on what you mean by "name the keys or any kind of string manipulation". If you're happy to encapsulate said naming of keys and string manipulation inside a stored proc so that you don't need to name keys when you're calling the procedure, then yes, you can:
drop procedure if exists spGetJson;
delimiter $$
create procedure spGetJson(pTableName varchar(45), pId int)
begin
select group_concat(concat("'", COLUMN_NAME, "', ", COLUMN_NAME) separator ',')
into @cols
from information_schema.columns
where TABLE_NAME = pTableName and TABLE_SCHEMA = database();
set @q = concat('select json_object(', @cols, ') from ', pTableName);
if pId is not null then
set @q = concat(@q, ' where id = ', pId);
end if;
set @q = concat(@q, ';');
prepare statement from @q;
execute statement;
deallocate prepare statement;
end $$
delimiter ;
然后您可以使用以下任一方法调用此proc:
You could then call this proc using either:
call spGetJson('people', 1);
call spGetJson('people', null);
这篇关于MySQL 5.7使用新的json功能将行作为json返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!