Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres select as json hash

I can select rows as JSON from Postgres e.g.

select row_to_json(t)
    from (
      select id, name from accounts
    ) t

Which returns each row in this format:

{"id":6001,"name":"Foo"}

I would like to get them in this format:

{ 6001: {"name":"Foo"} }

Is this possible?

Edit:

This will get me the proper format for one row:

select json_build_object(id,json_build_object('name',name)) from accounts

But what I'm ultimately after is all rows in a single hash indexed by key, e.g.

{ 
  6001: {"name":"Foo"},
  6002: {"name":"Bar"},
  6003: {"name":"Baz"},
}

This gets me closer:

select array_to_json(array_agg(json_build_object(id,json_build_object('name',name))))
from accounts

But it's still not quite there, producing an array of hashes:

[
  { 6001: {"name":"Foo"} },
  { 6002: {"name":"Bar"} },
  { 6003: {"name":"Baz"} },
]
like image 490
jemminger Avatar asked Jun 13 '26 18:06

jemminger


1 Answers

You're trying to aggregate, so use the aggregate function json_object_agg(), which "aggregates name/value pairs as a JSON object". The id is your key, and the value you can create with json_build_object():

select json_object_agg(id, json_build_object('name', name))
from accounts
like image 104
Dan Getz Avatar answered Jun 16 '26 07:06

Dan Getz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!