简体   繁体   English

PostgreSQL:动态查询到JSON数组

[英]PostgreSQL: Dynamic Query into JSON Array

I would like to execute a dynamic query using the EXECUTE statement and put the result into a json array. 我想使用EXECUTE语句执行动态查询,并将结果放入json数组。

I am getting 我正进入(状态

SQL Error [22P02]: ERROR: malformed array literal: "[malformed array literal: "[{"id": "1"}]" Detail: "[" must introduce explicitly-specified array dimensions. Where: PL/pgSQL function .... SQL错误[22P02]:错误:格式不正确的数组文字:“ [格式不正确的数组文字:” [{“ id”:“ 1”}]“”详细信息:“ [”必须引入显式指定的数组尺寸。PL / pgSQL函数....

Here is what I have so far. 这是我到目前为止所拥有的。

CREATE or replace function my_function()
returns json[] as $$
declare result json[];
begin
    execute '
        SELECT array_to_json(array_agg(t)) from (
            select ....
        ) t;
    ' into result;

    -- doing some stuff with the array

    return result;
END;
$$ language 'plpgsql';

As the user "a_horse_with_no_name" stated. 如用户“ a_horse_with_no_name”所述。 array_to_json does return a json object and NOT a json array. array_to_json确实返回json对象,而不是json数组。

In my case i could achieve what i want using 就我而言,我可以实现我想要的功能

CREATE or replace function my_function()
returns json as $$
declare result json;
begin
    execute '
        SELECT (''{ "data": '' || json_agg(t)::text || ''}'')::json from (
            select ....
        ) t;
    ' into result;

    -- doing some stuff with the array

    return result;
END;
$$ language 'plpgsql';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM