json - 对未知键的 Postgres JSON 查询

标签 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
           }
         ]
       }
}

我知道该文档的结构将是相同的,但键可以是任何东西。我可以自己拉出 key

select jsonb_object_keys(column) from table; 

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

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

最佳答案

是这样的:

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

还有一个 where 子句:

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

关于json - 对未知键的 Postgres JSON 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51756242/

相关文章:

java - org.postgresql.util.PSQLException : ERROR: function st_dwithin(geometry, double , double )不存在

postgresql - postgreSQL 中以逗号分隔的 jsonb 元素的串联

arrays - PostgreSQL:计算嵌套在 JSONB 列中的唯一数组值的出现次数?

ruby-on-rails - 像普通 ActiveRecord 属性一样访问 JSONB 字段

java - 从 Youtube API 获取视频 URL

sql - 在 Postgresql 中查找最近的不同记录并按 created_at 排序

jquery - $.getJSON 未检索文件

postgresql - 重启postgres服务的问题

python - 如何使具有内部类 JSON 的类可序列化

json - 控制 KeyValuePair<DateTime, long> 键的序列化格式