0

I have a table in a Postgres database that contains users, with their attributes stored as JSONB. The attributes can vary per user, and can be strings or lists of strings. Example snippets for two users:

select username, attributes from idp_accounts where username in ('visser', 'peter');
 username |                                                                  attributes                                                                  
----------+----------------------------------------------------------------------------------------------------------------------------------------------
 peter    | {"dn": "Peter Vonk", "sHO": "hei.foobar1.zz", "ePSA": ["[email protected]", "[email protected]"], "email": "[email protected]"}
 visser   | {"cn": "Dick Visser", "sn": "Visser", "uid": ["visser"], "mail": ["[email protected]", "[email protected]"], "displayName": "Dick Visser"}
(2 rows)

I'm looking for a way to select all attributes for a user as columns, so that the results looks like this:

ssp=> select username, ????attributes???? from idp_accounts where username = 'visser';
 username |       cn     |    sn     |   uid       |                   mail                         |  displayName
----------+--------------+-----------+-------------+------------------------------------------------+----------------
 visser   | Dick Visser  |  Visser   | ["visser"]  |  ["[email protected]", "[email protected]"]  |  Dick Visser
(1 row)

I've been over the various JSON functions but can't seem to get the result I'm looking for.

2
  • You'll have to specify the column names and types, there's no way around that. You can use jsonb_to_record(attributes), see the duplicates for examples Commented Apr 11, 2024 at 23:22
  • Actually, jsonb_populate_record() is typically the best (fastest, safest, cleanest) option. Especially with a given target table. I added a link. Commented Apr 12, 2024 at 1:52

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.