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?
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With