How can I get all keys from a JSON column in Postgres?

JsonPostgresql

Json Problem Overview


If I have a table with a column named json_stuff, and I have two rows with

{ "things": "stuff" } and { "more_things": "more_stuff" }

in their json_stuff column, what query can I make across the table to receive [ things, more_things ] as a result?

Json Solutions


Solution 1 - Json

Use this:

select jsonb_object_keys(json_stuff) from table;

(Or just json_object_keys if you're using just json.)

The PostgreSQL json documentation is quite good. Take a look.

And as it is stated in the documentation, the function only gets the outer most keys. So if the data is a nested json structure, the function will not return any of the deeper keys.

Solution 2 - Json

WITH t(json_stuff) AS ( VALUES
  ('{"things": "stuff"}'::JSON),
  ('{"more_things": "more_stuff"}'::JSON)
)
SELECT array_agg(stuff.key) result 
FROM t, json_each(t.json_stuff) stuff;

Solution 3 - Json

Here is the example if you want to get the key list of each object:

select array_agg(json_keys),id from (
select json_object_keys(json_stuff) as json_keys,id from table) a group by a.id

Here id is the identifier or unique value of each row. If the row cannot be distinguished by identifier, maybe it's better to try PL/pgSQL.

Solution 4 - Json

Insert json_column and table

select distinct(tableProps.props) from (
select jsonb_object_keys(<json_column>) as props from <table>
) as tableProps

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionverygoodsoftwarenotvirusView Question on Stackoverflow
Solution 1 - JsonSevanteriView Answer on Stackoverflow
Solution 2 - JsonDmitry SView Answer on Stackoverflow
Solution 3 - JsonnatsuapoView Answer on Stackoverflow
Solution 4 - JsonJackstineView Answer on Stackoverflow