gpt4 book ai didi

json - 从 JSON 对象中检索数据

转载 作者:行者123 更新时间:2023-11-29 11:47:25 26 4
gpt4 key购买 nike

有问题是根据通过过程传递的 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 的新手。请帮助。

最佳答案

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)

关于json - 从 JSON 对象中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34531092/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com