未知键上的Postgres JSON查询

时间:2018-08-08 22:00:18

标签: json postgresql jsonb

我有一个jsonb列,其中的结构始终保持不变,但是json中的键可能会更改。例如,

{
   "key-12345": 
    {
       "values-12345": [
          {"type": 5200, 
           "source": "somesource", 
           "messageid": 707643203507, 
           "timestamp": "2018-07-26T21:25:42.612Z", 
           "destination": "somedestination", 
           "previouslyRouted": false
          }, 
          {"type": 5200, 
           "source": "anothersource", 
           "messageid": 707643203507, 
           "timestamp": "2018-07-26T21:26:01.542Z", 
           "destination": "anotherdestination", 
           "previouslyRouted": false
           }
         ]
       },

   "key-6789": 
    {
       "values-34512": [
          {"type": 5200, 
           "source": "yetantohersomesource", 
           "messageid": 707643203507, 
           "timestamp": "2018-07-26T21:25:42.612Z", 
           "destination": "yetanothersomedestination", 
           "previouslyRouted": false
          }, 
          {"type": 5200, 
           "source": "anothersource", 
           "messageid": 707643203507, 
           "timestamp": "2018-07-26T21:26:01.542Z", 
           "destination": "anotherdestination", 
           "previouslyRouted": false
           }
         ]
       }
}

我知道该文档的结构将相同,但是键可以是任何东西。我可以用

自己拔出钥匙
select jsonb_object_keys(column) from table; 

很容易,但是我不知道如何提取分配给该键的对象并对其进行处理。如何根据键的值而不是值从jsonb对象中进行选择。

select object from document where json_key = 'key-12345';

2 个答案:

答案 0 :(得分:0)

使用运算符-> Get JSON object field by key:

select json_column->'key-12345'
from my_table;

或函数jsonb_each()

select key, value
from my_table
cross join jsonb_each(json_column);

DbFiddle.

答案 1 :(得分:0)

这是怎么做的:

SELECT object->>'key-12345' FROM document;

并带有 where 子句:

SELECT * FROM document WHERE object->>'key-12345' IS NOT NULL;