使用Postgres查询访问JSON内的数组
我有一个数据类型为json的表,我需要查询其中的一个属性 该列中的数据如下所示:使用Postgres查询访问JSON内的数组,json,postgresql,Json,Postgresql,我有一个数据类型为json的表,我需要查询其中的一个属性 该列中的数据如下所示: { "id": 7008, "access_links": [ { "product_code": "PRODUCT-1", "link": "https://some.url" }, { "product_code": "PRODUCT-2", "link": "https://someOther.url" } ],
{
"id": 7008,
"access_links": [
{
"product_code": "PRODUCT-1",
"link": "https://some.url"
},
{
"product_code": "PRODUCT-2",
"link": "https://someOther.url"
}
],
"library_id": "2d1203db-75b3-43a5-947c-8555b48371db"
}
[{"product_code":"PRODUCT-1","link":"https://some.url"},{"product_code":"PRODUCT-2","link":"https://someOther.url"}]
我需要能够提取和过滤的产品代码嵌套在访问链接内
我可以使用此查询获得一层深度:
选择
courses.course\u元数据->“访问链接”作为访问链接
从…起
课程
这似乎让我进入了专栏,但我不能再问下去了
我从查询中收到的输出如下所示:
{
"id": 7008,
"access_links": [
{
"product_code": "PRODUCT-1",
"link": "https://some.url"
},
{
"product_code": "PRODUCT-2",
"link": "https://someOther.url"
}
],
"library_id": "2d1203db-75b3-43a5-947c-8555b48371db"
}
[{"product_code":"PRODUCT-1","link":"https://some.url"},{"product_code":"PRODUCT-2","link":"https://someOther.url"}]
我尝试过使用->>和>>运算符,但它们都抱怨数组没有以{开头。还值得注意的是,列是JSON的数据类型,而不是JSONB,因此@>运算符不起作用
我在这里遗漏了什么?这有帮助吗
select
json_array_elements (x->'access_links')->'product_code' as product_code
from
(select '{
"id": 7008,
"access_links": [
{
"product_code": "PRODUCT-1",
"link": "https://some.url"
},
{
"product_code": "PRODUCT-2",
"link": "https://someOther.url"
}
],
"library_id": "2d1203db-75b3-43a5-947c-8555b48371db"
}'::json x
) as v
;
产品代码
产品-1
PRODUCT-2Perfect!这正是我所需要的。我已经看到了json_array_元素,但找不到适合我尝试的用例。