从JSON对象检索数据

时间:2015-12-30 14:05:39

标签: json postgresql

有问题是根据通过程序传递的langtype选择local_desc。

样本表和数据供您参考

create table test (local_id numeric, local_name json);

insert into test values (1, '{"language": [{"langtype": "EN", "Lang_desc": "English Smithline group"},{"langtype": "TH", "Lang_desc": "Thai Smithline group"}, {"langtype" :"AR", "Lang_desc":"Arabic Smithline group"}]}')

select local_id,local_name from test -- works fine

select local_id,local_name->'language' as lang from test    --- works fine

select local_id,local_name->'language'->>'Lang_desc' as lang from test where local_name->'language'->>'langtype'='EN' ---This query does not retrieve any data.. I want to get lang_desc based on the language parameter.. 

我是JSON和postgres的新手。帮助。

1 个答案:

答案 0 :(得分:2)

local_name->'language'指向json数组。您应该使用json_array_elements()解压缩数组:

select local_id, elem
from test, json_array_elements(local_name->'language') elem;

 local_id |                            elem                            
----------+------------------------------------------------------------
        1 | {"langtype": "EN", "Lang_desc": "English Smithline group"}
        1 | {"langtype": "TH", "Lang_desc": "Thai Smithline group"}
        1 | {"langtype" :"AR", "Lang_desc":"Arabic Smithline group"}
(3 rows)

使用以上查询选择过滤后的数据:

select local_id, elem->>'Lang_desc' lang_desc
from (
    select local_id, elem
    from test, json_array_elements(local_name->'language') elem
    ) sub
where elem->>'langtype' = 'EN';

 local_id |        lang_desc        
----------+-------------------------
        1 | English Smithline group
(1 row)