0

There is a column "fields" in my table. It contains something like this:

{"creative_url": {"required": true, "data_type": "string"}}

or

{"creative_name_field": {"required": false, "data_type": "integer"}}

So, different keys in main dict.

I want to select all rows with:

"required": true

Trying something like :

select *
from my_table
where fields @> '{"required":true}'

But it shows me nothing (0 rows found).

Postgres documentation doesn't give me any other method to do this. What's the problem?

2 Answers 2

1

The @> operator checks only at top level.
You can use the jsonb_object_keys function to get the top level keys of your jsonb objects (use json_object_keys if you're using the json type instead).

WITH j(json) AS (
  VALUES 
    ('{"creative_url": {"required": true, "data_type": "string"}}'::jsonb),
    ('{"creative_name_field": {"required": false, "data_type": "integer"}}')
)
SELECT 
  json,
  json->k @> '{"required": true}' AS is_required
FROM j, jsonb_object_keys(json) s(k)
;
┌──────────────────────────────────────────────────────────────────────┬─────────────┐
│                                 json                                 │ is_required │
├──────────────────────────────────────────────────────────────────────┼─────────────┤
│ {"creative_url": {"required": true, "data_type": "string"}}          │ t           │
│ {"creative_name_field": {"required": false, "data_type": "integer"}} │ f           │
└──────────────────────────────────────────────────────────────────────┴─────────────┘
(2 rows)
Sign up to request clarification or add additional context in comments.

1 Comment

Really difficult to understand this query) But it worked!
0

Though answer is accepted already and OP is satisfied with answer but I am still adding solution to those who may need helps. It seems you have two level search in the db with json object column. The simplest way to get the record is

select * from my_table where fields->'creative_name_field'->>'required'='true' OR fields->'creative_url'->>'required'='true';

There is other way of doing this but I haven't tested it

select * from my_table where fields->{'creative_url', 'creative_name_field'}->>'required'='true';

There is one catch here is to use the parent key before the is_required sub-key check. Hope This will help.

2 Comments

This example will not work if I want to select all fields ('creative_name_field' and 'creative_url') with required='true'
Oh I missed the point So, different keys in main dict.. But now I have corrected the solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.