PostgreSQL,根据并行属性的值获取JSON对象字段

时间:2018-08-20 21:19:54

标签: json postgresql

假设我们正在处理一个JSON对象,其中可以有多个具有相同结构的子节点,并且我们想要获取属性B,C,D等的值。其中属性A等于特定值。下面是一个示例。

{
"addresses": [{
    "type": "home",
    "address": "123 fake street",
    "zip": "24301"
}, {
    "type": "work",
    "address": "346 Main street",
    "zip": "24352"
}, {
    "type": "PO Box",
    "address": "PO BOX 132, New York, NY",
    "zip": "10001"
}, {
    "type": "second",
    "address": "1600 Pennsylvania Ave.",
    "zip": "90210"
}]}

PostgreSQL中是否有任何JSON运算符可用来获取邮政编码,其地址类型为“工作”或“家”?我正在寻找https://www.postgresql.org/docs/current/static/functions-json.html,但没有找到我想要的东西。

1 个答案:

答案 0 :(得分:2)

您需要“取消嵌套”(即规范化)数据,然后可以对其应用WHERE条件:

select t.adr ->> 'zip', t.adr ->> 'address'
from the_table
  cross join lateral jsonb_array_elements(the_column -> 'addresses') as t(adr)
where t.adr ->> 'type' in ('work', 'home');

在线示例:http://rextester.com/TDB99535