在 Postgresql 中查询复杂 JSON 的简洁方法

Clean way to query complex JSON in Postgresql

我有 JSON 数据存储在我的 postgresql 9.5 数据库的 JSONB 字段中。

有没有办法在不知道哪一列是子对象的情况下制作子对象列?

JSON 有问题的例子:

{
   "a":1,
   "b":[1,2,3],
   "c":"bar",
   "d":{
      "key1":"value1",
      "key2":"value2"
   }
 }

我可以使用以下方法从 JSON 对象中获取所有键。

SELECT * FROM json_object_keys('{"a":1,"b":[1,2,3],"c":"bar", "d":{"key1":"value1", "key2":"value2"}}')

那时我可以使用 json_to_record() 但我想将该列拆分为它们自己的单独字段。

select * from json_to_record('{"a":1,"b":[1,2,3],"c":"bar", "d":{"key1":"value1", "key2":"value2"}}') as x(a int, b text, c text, d text)

让我明白

a| b       | c   | d     
1| [1,2,3] | bar | {"key1":"value1", "key2":"value2"}

有没有办法找回这样的东西,最好是在单个查询中?

--------------------------------------------------------------------
a| b       | c   | d                                  | key1  | key2     
1| [1,2,3] | bar | {"key1":"value1", "key2":"value2"} |value1 |value2
WITH t(v) AS ( VALUES
  ('{
     "a":1,
     "b":[1,2,3],
     "c":"bar",
     "d":{
        "key1":"value1",
        "key2":"value2"
     }
   }'::JSONB)
)
SELECT x1.*,x2.* FROM t,
    jsonb_to_record(v) as x1(a int,b text,c text,d jsonb),
    jsonb_to_record(v->'d') as x2(key1 text,key2 text);

结果:

 a |     b     |  c  |                  d                   |  key1  |  key2  
---+-----------+-----+--------------------------------------+--------+--------
 1 | [1, 2, 3] | bar | {"key1": "value1", "key2": "value2"} | value1 | value2
(1 row)