简体   繁体   English

如何过滤json嵌套键的值

[英]How to filter a value of nested key of json

I have a table in PostgreSQL我在 PostgreSQL 有一张桌子

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

And the data's present inside this table are这张表中的数据是

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

I need to fetch the details of all account having rootcompanyid in (5).我需要在 (5) 中获取所有具有rootcompanyid的帐户的详细信息。 IF part of any **rootcompanyid's ** are present in any of the account details should display the result.如果任何 **rootcompanyid 的 ** 部分存在于任何帐户详细信息中,则应显示结果。 So output should contain account_id --> 1 and 3 rows所以 output 应该包含account_id --> 1 和 3

The below query is fetching only the last row (account_id = 3) not the first row下面的查询只获取最后一行 (account_id = 3) 而不是第一行

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.预期 Output :如果任何 **rootcompanyid 的 ** 部分存在于任何帐户详细信息中,则应显示结果。

account_id帐户ID condition状况
1 1个 [{"action":"read","subject":"rootcompany","conditions":{"rootcompanyid":{"$in":[35,20,5,6]}}}] [{"action":"read","subject":"rootcompany","conditions":{"rootcompanyid":{"$in":[35,20,5,6]}}}]
3 3个 [{"action":"read","subject":"rootcompany","conditions":{"rootcompanyid":{"$in":[5]}}}] [{"action":"read","subject":"rootcompany","conditions":{"rootcompanyid":{"$in":[5]}}}]

That's easily done with the JSON containment operator:使用 JSON 包含运算符可以轻松完成此操作:

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:如果要搜索多个数组元素,请将上述条件中的两个与OR一起使用或使用 JSONPATH 查询:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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