首页 > 解决方案 > 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;
$$

非常感谢,马特

标签: jsonpostgresql

解决方案


它可以被解析,但问题是你将如何处理响应?

如果您只想在结果中看到它,那么最快的方法是在 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)


推荐阅读