mySQL 5.7 return row as json using new json features

ε祈祈猫儿з 提交于 2019-12-07 04:51:05

问题


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.

Example:

TABLE: people
id     name     age
1      bob      54
2      jay      32
3      john     10

SELECT * FROM people where id = 1

would return

{"id":1,"name":"bob","age":54}

Or even better

SELECT * FROM people

would return an array of all 3 objects

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')

would return a key value JSON object.


回答1:


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 ;

You could then call this proc using either:

call spGetJson('people', 1);
call spGetJson('people', null);


来源:https://stackoverflow.com/questions/35324795/mysql-5-7-return-row-as-json-using-new-json-features

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!