Postgresql JSON column check key exists

Viewed 18024

I have wrote query like this to check json column has key

SELECT *
FROM "details" 
where ("data"->'country'->'state'->>'city') is not null; 

but i need to write query which will select row if "data" contains "city"

json structure of data is not consistent.

3 Answers

You can use ?:

SELECT *
FROM "details" 
WHERE data->'country'->'state' ? 'city';

You can convert your json to text and search for the key with LIKE

SELECT *
FROM "details"
WHERE "data"::text LIKE '%"city":%'
Related