0

I'm using Postgres database and have a table as below

Table Name: Test

id    firstname    lastname
 1     Sam          Crews
 2     John         Dave

I'm trying to get result set back in below JSON format but with no luck

Expected:

[{"1": {"firstname": "Sam", "lastname": "Crews"}},
 {"2": {"firstname": "John", "lastname": "Dave"}}
]

I tried using row_to_json, json_build_object functions but the output is bit different (as below).

Actual:

[{"id": "1", "firstname": "Sam", "lastname": "Crews"},
 {"id": "2", "firstname": "John", "lastname": "Dave"}
]

Any pointers on how to achieve expected result would be greatly appreciated.

Thank you!

2 Answers 2

3

row_to_json() will always use all column names to create the keys in the JSON document. If you only want two columns, you need to explicitly specify them.

You also want a nested JSON object, so you need to nest the methods to create one:

select json_agg(json_build_object(
                 id, 
                 json_build_object('firstname', firstname, 'lastname', lastname))
                )
from the_table;

Klin made me realize that with Postgres 9.6 you can simplify the creation of the firstname/lastname object:

select json_agg(json_build_object(id, to_jsonb(the_table) - 'id'))
from the_table;
Sign up to request clarification or add additional context in comments.

Comments

3
with my_table(id, firstname, lastname) as (
values
(1, 'Sam', 'Crews'),
(2, 'John', 'Dave')
)

select jsonb_agg(obj)
from my_table,
jsonb_build_object(id, to_jsonb(my_table)- 'id') obj

                                              jsonb_agg                                               
------------------------------------------------------------------------------------------------------
 [{"1": {"lastname": "Crews", "firstname": "Sam"}}, {"2": {"lastname": "Dave", "firstname": "John"}}]
(1 row) 

Comments

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.