-1

I have created a function in postgres that returns json.

The function is used in an API and returns this:

[
    {
        "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$;
GMB
  • 216,147
  • 25
  • 84
  • 135

2 Answers2

1

You can use json aggregation. 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
GMB
  • 216,147
  • 25
  • 84
  • 135
0
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
    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)

end;
$BODY$;
Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
sys
  • 330
  • 3
  • 15