2

I'm trying to retrieve a json array containing the rows returned with this function:

CREATE OR REPLACE FUNCTION get_users_list() 
RETURNS TABLE (
id INTEGER,
name VARCHAR,
surname VARCHAR,
fkrole INTEGER,
username VARCHAR
) as $$
BEGIN

RETURN QUERY SELECT users.id, users.name,
                    users.surname, users.fkrole, 
                    users.username 
FROM users;
END;
$$ LANGUAGE plpgsql;

Can anyone give me a hint? How can I convert multiple rows into a single JSON array?

Thanks!

1 Answer 1

6

Give this a try:

SELECT JSON_AGG(src) AS my_json_array
FROM (
  SELECT 
    users.id, 
    users.name, 
    users.surname, 
    users.fkrole, 
    users.username 
  FROM users
) src
;

This will give you all the rows from your "src" query returned as a single json array.

http://www.sqlfiddle.com/#!17/6241a/2

Here's some more info on the Postgres JSON functions: https://www.postgresql.org/docs/10/static/functions-json.html

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the hint! For future references the working fuction is CREATE OR REPLACE FUNCTION get_users_list() RETURNS JSON as $$ DECLARE users JSON; BEGIN SELECT json_agg(src) INTO users FROM ( SELECT users.id, users.name, users.surname, roles.role, users.username FROM users, roles WHERE users.fkrole = roles.id ) src ; RETURN users; END; $$ LANGUAGE plpgsql;
My pleasure. :)
You got it my friend :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.