This was copied from the answer to another question.
There's another function called json_object_agg
, which can generate an object instead of an array.
It can be used like this:
select json_object_agg(your_table.id, your_table) from your_table;
Output like this:
{ "1" : {"id":1,"name":"abc","age":18,"sex":"m"}, "2" : {"id":2,"name":"abc","age":18,"sex":"f"}, "4" : {"id":4,"name":"abc","age":18,"sex":"f"} }
Related functions include: json_agg
, jsonb_agg
, json_object_agg
, jsonb_object_agg
. (There is also xmlagg
; for more, you can check this doc). One of their differences is that the jsonb
versions will remove duplicate keys, while the json
versions will retain all content even if the keys are duplicated.