我在 hotel_data
字段中有 JSON 数据,如下所示:
{
"title":"foo",
"description":[
{
"locale":"pt",
"content":"pt text"
},
{
"locale":"fr",
"content":"fr text"
}
]
}
我只想选择description
fr
描述。可以使用 Postgres 吗?
我正在尝试使用 ->>
但它不起作用...
SELECT
hotel_data->'description'->>'locale' = 'fr' AS description
FROM hotel LIMIT 1;
注意:
我不想使用 SELECT *
...
异常输出:{description: "fr text"}
最佳答案
您可以使用横向连接和 json_to_recordset
将 json 数组扩展为一组记录。然后,您可以在生成的记录中过滤 locale
列,最后用您的预期结果重组一个新的 json 对象:
select json_build_object('description', d.content) hotel_data_descr_fr
from
mytable,
json_to_recordset(hotel_data->'description') as d("locale" text, "content" text)
where d.locale = 'fr'
with mytable as (
select '{
"title":"foo",
"description":[
{
"locale":"pt",
"content":"pt text"
},
{
"locale":"fr",
"content":"fr text"
}
]
}'::json hotel_data
)
select json_build_object('description', d.content) hotel_data_descr_fr
from
mytable,
json_to_recordset(hotel_data->'description') as d("locale" text, "content" text)
where d.locale = 'fr'
| hotel_data_descr_fr | | :------------------------- | | {"description": "fr text"} |
关于json - 如何从 Postgres 中的 json 中选择查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58468417/