【问题标题】:How do I select all from a nested array of JSON objects?如何从 JSON 对象的嵌套数组中选择所有对象?
【发布时间】:2021-10-30 04:04:29
【问题描述】:

我有一个 PostgreSQL 表,其中每一行都包含如下所示的 JSON 对象:

{
   "Metadata":{
      ...
   },
   "NestedArray":[
      {
         ...,
         ...,
         "Coordinates":[
            {
               "id":"1000",
               "X":"...",
               "Y":"..."
            },
            {
               "id":"1001",
               "X":"...",
               "Y":"..."
            },
            {
               "id":"1003",
               "X":"...",
               "Y":"..."
            }
         ]
      }
   ]
}

所以每个对象都包含一个NestedArray,其中包含另一个名为Coordinates的嵌套数组。

MyObject.NestedArray[].Coordinates[]

我要做的是在我的 PostgreSQL 表中查询一个 JSON 列,其中包含上述对象,并​​获取所有 Coordinates 对象的结果集。

所以这基本上就是我想要的结果:

id X Y
1001 . .
1002 . .
1003 . .
1004 . .
1005 . .
1006 . .

我该怎么做?

【问题讨论】:

    标签: json postgresql


    【解决方案1】:

    我不认为 jsonb_array_elements() 在这种情况下会起作用,因为有两个嵌套级别的 json 数组。这应该预先测试:

    SELECT r.item ->> 'id' as id
         , r.item ->> 'X' as X
         , r.item ->> 'Y' as Y
    FROM your_table
    CROSS JOIN LATERAL jsonb_path_query(your_json_column :: jsonb, '$.NestedArray[*].Coordinates[*]') AS r(item)
    

    【讨论】:

      【解决方案2】:

      您需要取消嵌套数组,然后您可以使用->> 运算符访问每个键:

      select e.item ->> 'id' as id, 
             e.item ->> 'x' as x,
             e.item ->> 'y' as y
      from the_table
        cross join jsonb_array_elements(the_column -> 'NestedArray') as c(o)
        cross join jsonb_array_elements(c.o -> 'Coordinates') as e(item)
      

      这假定the_column 是用数据类型jsonb 定义的(它应该是)。如果不是,请改用json_array_elements()

      Online example

      【讨论】:

      • 取消嵌套数组是什么意思?我无法控制 JSON 文档的结构。
      • jsonb_array_elements 将取消嵌套数组
      猜你喜欢
      • 2019-08-11
      • 2019-08-16
      • 2021-08-25
      • 2020-07-20
      • 2015-08-02
      • 2017-11-27
      • 2013-04-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多