postgresql 如何解析存储在json数组中的非固定路径的特定元素?

n3ipq98p  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(1)|浏览(141)

PostgreSQL数据库中存储JSON数组的表。我无法解析具体的键值,因为它们的顺序不固定。例如,

[
      {
        "name": "Wu"
      },
      {
        "age": 20,
      },
      {
        "Sex": "Male"
      }
]

字符串
下一行存储如下:

[
      {
        "Sex": "Female"
      },
      {
        "age": 10
      },
      {
        "name": "Chen",
      }
]


我看了PostgreSQL的文档,好像那些函数总是需要一个固定的路径来解析。我该怎么解决这个问题呢?

pxq42qpu

pxq42qpu1#

解嵌套数组并使用聚合函数重新展平它。

create temp table t(id int,j json) ; 
insert into t values(42,'[{"name": "Wu"},{"age": 20},{"Sex": "Male"}]'),(86,'[{"Sex": "Female"},{"age": 10 },{"name": "Chen" }]');


select t.id, 
    max(e->>'age') as age,
    max(e->>'name') as name
FROM t, 
    LATERAL json_array_elements(t.j) AS e
GROUP BY t.id;


SELECT t.id, 
    max(e->>'age') as age,
    max(e->>'Sex') as sex
FROM t, 
    LATERAL json_array_elements(t.j) AS e
GROUP BY t.id
HAVING  max(e->>'name') = 'Chen';

字符串

相关问题