json - PostgreSQL - 解析嵌套的 JSON 参数
问题描述
我在我的 Postgres 经验中很年轻,所以我希望这不是太补救:)
如果嵌套的 JSON 在 PostgreSQL 中作为变量传递,是否可以在不先将其转储到临时表的情况下对其进行解析?
假设我想从下面的示例中获取母亲的名字。SELECT 语句会是什么样子?
do
$$
declare persons json =
'{
"name":"Sally",
"spouse":
{
"name":"Alex",
"parents":
{
"father":"Rafael",
"mother":"Ofelia"
},
"phones":
[
{
"type":"work",
"number":"619-555-1212"
},
{
"type":"cell",
"number":"012-345-6789"
}
]
}
}';
begin
/* ??? */
end;
$$
非常感谢,马特
解决方案
它可以被解析,但问题是你将如何处理响应?
如果您只想在结果中看到它,那么最快的方法是在 CTE 中定义您的 json:
with p as (
select '{
"name":"Sally",
"spouse":
{
"name":"Alex",
"parents":
{
"father":"Rafael",
"mother":"Ofelia"
},
"phones":
[
{
"type":"work",
"number":"619-555-1212"
},
{
"type":"cell",
"number":"012-345-6789"
}
]
}
}'::jsonb as persons
)
select persons->'spouse'->'parents'->>'mother'
from p;
?column?
----------
Ofelia
(1 row)
推荐阅读
- javascript - CSS:每隔几秒改变一次背景?
- amazon-web-services - 来自 EC2 实例的 S3 完全访问配置
- java - FlatMap 一个可迭代对象并将其组合回可迭代对象
- c++ - 有没有办法在 Python 中做“模板基类”?
- docker - Dockerfile 可以 COPY 文件到声明的卷中,但是 RUN 不能创建文件?
- firebase - 加载设置 Firebase 设置时发生未知错误。Firebase 控制台故障
- regex - 如何在 Apache 中通过 URL 设置 HTTP 标头差异
- android - 从共享对话框获取发布事件
- css - 更改图像高度而不拉伸图像
- matlab - 在 Matlab 中编写乘积的特殊情况