如何检查包含字段和类似值的JSON字符串?

时间:2018-12-13 11:23:20

标签: sql json postgresql

我有一个JSON:

[{"name": "Criss", "idNumber": "2177"}, {"name": "Kate", "idNumber": "6234"}]
[{"name": "Alex"}, {"name": "Paul"}]
[{"name": "Emma", "idNumber": "2056"}, {"name": "Isabella", "idNumber": "8832"}]
[{"name": "Olivia", "idNumber": "2163"}, {"name": "Greck", "idNumber": "8585"}]

我需要找到所有行,其中包含字段 idNumber ,并且值也必须为like '21%'

我使用@>运算符检查是否包含。但是如何检查LIKE

预期结果:

[{"name": "Criss", "idNumber": "2177"}, {"name": "Kate", "idNumber": "6234"}]
[{"name": "Olivia", "idNumber": "2163"}, {"name": "Greck", "idNumber": "8585"}]

1 个答案:

答案 0 :(得分:1)

您需要取消嵌套数组的顺序才能在其中的每个元素上使用运算符。

这可以在相关的子查询中完成:

select t1.*
from the_table t1
where exists (select *
              from jsonb_array_elements(t1.d) as x(e)
              where x.e ->> 'idNumber' like '21%');

无需单独测试密钥idNumber的存在,因为如果密钥不存在,->>将返回null

在线示例:https://rextester.com/KZY46113