简体   繁体   中英

How to filter a value of nested key of json

I have a table in PostgreSQL

CREATE TABLE IF NOT EXISTS account_details
(
    account_id integer,
    condition json
);

And the data's present inside this table are

account_id condition
1 [{"action":"read","subject":"rootcompany","conditions":{"rootcompanyid":{"$in":[35,20,5,6]}}}]
2 [{"action":"read","subject":"rootcompany","conditions":{"rootcompanyid":{"$in":[1,4,2,3,6]}}}]
3 [{"action":"read","subject":"rootcompany","conditions":{"rootcompanyid":{"$in":[5]}}}]

I need to fetch the details of all account having rootcompanyid in (5). IF part of any **rootcompanyid's ** are present in any of the account details should display the result. So output should contain account_id --> 1 and 3 rows

The below query is fetching only the last row (account_id = 3) not the first row

SELECT *
  FROM account_details
 WHERE ((condition->0->>'conditions')::json->>'rootcompanyid')::json->>'$in' = '[5]';

Expected Output : IF part of any **rootcompanyid's ** are present in any of the account details should display the result.

account_id condition
1 [{"action":"read","subject":"rootcompany","conditions":{"rootcompanyid":{"$in":[35,20,5,6]}}}]
3 [{"action":"read","subject":"rootcompany","conditions":{"rootcompanyid":{"$in":[5]}}}]

That's easily done with the JSON containment operator:

WHERE condition::jsonb @> '[ { "conditions": { "rootcompanyid": { "$in": [5] } } } ]'

If you want to search for more than a single array element, either use two of the above conditions with OR or use a JSONPATH query:

WHERE jsonb_path_exists(
         condition::jsonb,
         '$[*].conditions.rootcompanyid.\$in[*] ? (@ == 5 || @ == 6)'
      )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM