从postgres json列中提取数组并映射它

che*_*ett 7 postgresql json postgresql-9.3

create table test(a json);

insert into test(a) 
values('{"orders":[{"orderId":1}, {"orderId":2, "status":"done"}, {"orderId":3}]}');
Run Code Online (Sandbox Code Playgroud)

鉴于上面的结构,我可以得到一个未完成的数组或一组orderIds吗?那么,我的意思是我可以用sql或plpgsql获取orderIds吗?

任何建议都会很棒!非常感谢你!

Cra*_*ger 11

一旦我修复了完全破坏的json,这只是一个LATERAL解包数组并过滤它的查询.

select (x->>'orderId')::integer
from test,
     json_array_elements(a->'orders') x 
where (x ->> 'status') IS DISTINCT FROM 'done';
Run Code Online (Sandbox Code Playgroud)

我用过,IS DISTINCT FROM所以我没有测试两者NULL(没有键)和!= 'done'.

  • 对于遇到此问题的其他任何人,您都需要在jsonb数据类型上使用jsonb_array_elements(请注意额外的B)。 (2认同)