Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 421
verygoodsoftwarenotvirus Avatar asked Mar 21 '16 20:03

verygoodsoftwarenotvirus


People also ask

How do I query a JSON column in PostgreSQL?

PostgreSQL has two native operators -> and ->> to query JSON documents. The first operator -> returns a JSON object, while the operator ->> returns text. These operators work on both JSON as well as JSONB columns. There are additional operators available for JSONB columns.

How do I check if a JSON key exists in Postgres?

In Postgres, if you select a key that does not exist it will return null. so u can check the existence of a key by checking the null value of that key.


2 Answers

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.

like image 75
Sevanteri Avatar answered Sep 27 '22 22:09

Sevanteri


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; 
like image 20
Dmitry S Avatar answered Sep 27 '22 23:09

Dmitry S