7

ROW_TO_JSON function in postgres converts a row of a table to a JSON object.

select row_to_json(result) from (select * from employee) as result;
select row_to_json(result) from (select * from student) as result;

Gives me three rows:

{"salary":null,"age":65,"address":null,"id":111,"name":"NAME"}
{"salary":null,"age":21,"address":null,"id":222,"name":"SURNAME"}
{"dob":"1997-03-02","name":"Mediocore","passed":true,"id":555}

The first two rows are from employee table whereas the last row is from student table.

What If I want to put the entire resultset from a single table in an array of JSON objects ? eg.

[{"salary":null,"age":65,"address":null,"id":111,"name":"NAME"}, {"salary":null,"age":21,"address":null,"id":222,"name":"SURNAME"}]as a single row instead of two separate rows.

Is there something equivalent to TABLE_TO_JSON ?

3
  • what version you run?.. Commented May 15, 2017 at 9:34
  • PostgreSQL 9.6 with pgAdmin 4 v4 Commented May 15, 2017 at 9:39
  • ah, then @a_horse_with_no_name gave best answer :) Commented May 15, 2017 at 9:39

1 Answer 1

10

Maybe I'm missing something but this looks like json_agg should do it.

You also don't need the derived table:

select json_agg(row_to_json(employee)) 
from employee;
Sign up to request clarification or add additional context in comments.

1 Comment

row_to_json is first json function, how did you know OPs not on 9.2?

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.