简体   繁体   English

在 Postgres 中返回 JSON

[英]Return JSON in Postgres

I have created a function in postgres that returns json.我在 postgres 中创建了一个返回 json 的函数。

The function is used in an API and returns this:该函数在 API 中使用并返回:

[
    {
        "jobfeed_beroepen_list": [
            {
                "profession_code": 3674,
                "profession_descr": "Manusje van alles (boodschappen, post en goederen)"
            },
            {
                "profession_code": 4107,
                "profession_descr": "Algemeen medewerker"
            }
        ]
    }
]

But I want it to return this:但我希望它返回这个:

[
    {
        "profession_code": 3674,
        "profession_descr": "Manusje van alles (boodschappen, post en goederen)"
    },
    {
        "profession_code": 4107,
        "profession_descr": "Algemeen medewerker"
    }
]

Question: what do I have to change in the code?问题:我必须在代码中更改什么?

--------------- this is the function -------------- --------------- 这是功能--------------

CREATE OR REPLACE FUNCTION api.fnc_jobfeed_beroepen(
    )
    RETURNS TABLE(jobfeed_beroepen_list jsonb) 
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
    ROWS 1000
AS $BODY$
DECLARE

BEGIN
jobfeed_beroepen_list := to_jsonb(array_agg(t)) FROM
                    (SELECT profession_code, profession_descr
                    FROM skillcv.jobfeed_beroepen
                    WHERE use = 1
                    ) AS t;
RETURN QUERY SELECT jobfeed_beroepen_list;

END;
$BODY$;

You can use json aggregation.您可以使用 json 聚合。 That would be:那将是:

return query 
    select jsonb_agg(
        jsonb_build_object(
            'profession_code',  profession_code, 
            'profession_descr', profession_descr
        )
    ) as res
    from skillcv.jobfeed_beroepen
    where use = 1

CREATE OR REPLACE FUNCTION api.fnc_jobfeed_beroepen( ) RETURNS TABLE(jobfeed_beroepen_list jsonb) LANGUAGE 'plpgsql'创建或替换函数 api.fnc_jobfeed_beroepen() 返回表(jobfeed_beroepen_list jsonb) LANGUAGE 'plpgsql'

COST 100
VOLATILE 
ROWS 1000

AS $BODY$ DECLARE作为 $BODY$ 声明

begin return query(select jsonb_agg( jsonb_build_object( 'profession_code', profession_code, 'profession_descr', profession_descr ) ) as res from skillcv.jobfeed_beroepen where use = 1)开始返回查询(选择 jsonb_agg(jsonb_build_object('profession_code',profession_code,'profession_descr',professional_descr)) 作为 res 来自 Skillcv.jobfeed_beroepen where use = 1)

end;结尾; $BODY$; $身体$;

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

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