I have a PostgreSQL 12.x
database. There is a column data
in a table typename
that contains jsonb
values. The actual JSON data is not fixed to a particular structure; these are some examples:
{"emt": {"key": " ", "source": "INPUT"}, "id": 1, "fields": {}}
{"emt": {"key": "Stack Overflow", "source": "INPUT"}, "id": 2, "fields": {}}
{"emt": {"key": "https://www.domain.tld/index.html", "source": "INPUT"}, "description": {"key": "JSONB datatype", "source": "INPUT"}, "overlay": {"id": 5, "source": "bOv"}, "fields": {"id": 1, "description": "Themed", "recs ": "1"}}
What I’m trying to do is to get all the JSON keys bound to objects that:
- Contain only two elements:
key
andsource
source
element must be bound to"INPUT"
Basically, for this example, the result should be: emt
, description
.
This is what I have so far, but it’s not quite working as expected:
select distinct jsonb_object_keys(data) as keys
from typename
where jsonb_path_exists(data, '$.** ? (@.type() == "string" && @ like_regex "INPUT")');
-- where jsonb_typeof(data -> ???) = 'object'
-- and jsonb_path_exists(data, '$.???.key ? (@.type() == "string")')
-- and jsonb_path_exists(data, '$.???.source ? (@.type() == "string" && @ like_regex "INPUT")');
2
Answers
I write for you sample, maybe you will need:
Some samples maybe need to you:
Sample1:
Sample2:
Sample3: