PostgreSQL难以从jsonb列中提取字段

时间:2017-01-19 15:17:29

标签: arrays json postgresql jsonb

使用PostgreSQL 9.5.5 给出以下示例列中的jsonb数据:

{
 "item_id": "123456",
 "action_information_1": [ {"value": "259", "action_type": "read"} ],
 "action_information_2": [ {"value": "93",  "action_type": "read"} ],
 "action_information_3": [ {"value": "53",  "action_type": "read"} ],
 "action_information_4": [ {"value": "35",  "action_type": "read"} ]
}

我很难以编程方式从'action_information_1'中提取'value',这将是259。

似乎语法与我见过的其他例子略有不同,上面的'''在'''前面有'''。

感谢任何帮助,谢谢

1 个答案:

答案 0 :(得分:2)

如果您修复了JSON文档中的语法错误,则可以使用以下方法:

with test_data (doc) as (
  values (
   '{
     "item_id": "123456",
     "action_information_1": [{"value": "259", "action_type": "read"}],
     "action_information_2": [{"value": "93", "action_type": "read"}],
     "action_information_3": [{"value": "53", "action_type": "read"}],
     "action_information_4": [{"value": "35", "action_type": "read"}]
    }'::json
  )
)
select doc -> 'action_information_1' -> 0 ->> 'value'
from test_data

doc -> 'action_information_1'获取该密钥的数组,-> 0返回第一个数组元素,然后->> 'value'获取与密钥value

或者,可以使用以下方法将其写得更短:

select doc #> '{action_information_1,0}' ->> 'value'
from test_data
相关问题