json - 如何在 Postgres 中从 json 中选择查询
问题描述
我在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 | | :------------------------- | | {“描述”:“fr 文本”} |
推荐阅读
- c# - 缩进在 C# 中使用 XDocument 编辑的 Xml 文件
- swift - 在 macOS 上呈现 Xcode 的构建成功警报等警报视图的正确方法是什么?
- ajax - fetch() 发布请求操作
- automation - 如何在 Word 365 文档中创建 AutoOpen 宏
- html - 使用缩小的浏览器窗口@media css 包装到底线
- javascript - 鼠标悬停时出现的小赢的名字是什么以及如何创建它
- c++ - 无法弄清楚如何在 c++ 中使用 winapi 设置 EM_SETLIMITTEXT 的值
- macos - 如何在 mac 上链接 linux?
- javascript - 创建可着色、可点击的网格 (javascript)
- c# - 循环通过两个不均匀的循环