【问题标题】:How to retrieve values from an array of json objects in PostgreSQL?如何从 PostgreSQL 中的 json 对象数组中检索值?
【发布时间】:2020-06-17 20:56:37
【问题描述】:

我有以下 json

[
   {
      "transition":"random_word",
      "from":"paris",
      "to":"porto",
      "date":{
         "date":"2020-05-28 11:51:25.201864",
         "timezone_type":3,
         "timezone":"Europe\/Paris"
      }
   },
   {
      "transition":"rainbow",
      "from":"porto",
      "to":"faro",
      "date":{
         "date":"2020-06-06 23:10:06.878539",
         "timezone_type":3,
         "timezone":"Europe\/Paris"
      }
   },
   {
      "transition":"banana",
      "from":"faro",
      "to":"rio_de_janeiro",
      "date":{
         "date":"2020-06-06 23:14:10.975099",
         "timezone_type":3,
         "timezone":"Europe\/Paris"
      }
   },
   {
      "transition":"hello",
      "from":"rio_de_janeiro",
      "to":"buenos_aires",
      "date":{
         "date":"2020-06-06 23:14:15.314370",
         "timezone_type":3,
         "timezone":"Europe\/Paris"
      }
   }
]

假设我想检索我的旅行者的最后一站(来自最后一个 json 对象的键“to”的值。这里:buenos_aires)和日期 (这里:2020-06-06 23:14:15.314370)。

如果我知道我想使用 PostgreSQL 来做这件事,我应该如何继续?

【问题讨论】:

    标签: json postgresql key-value data-extraction


    【解决方案1】:

    如果用“last”表示元素在数组中出现的顺序,则可以使用jsonb_array_length() 获取数组的长度并使用它来获取最后一个元素:

    select (the_json_column -> jsonb_array_length(the_json_column) - 1) ->> 'to' as "to",
           (the_json_column -> jsonb_array_length(the_json_column) - 1) #>> '{date,date}' as "date"
    from the_table 
    

    表达式jsonb_array_length(the_json_column) - 1 计算数组中“最后一个”元素的索引。

    如果您的列定义为 json 而不是 jsonb(应该是),则需要使用等效的 json_array_length()

    【讨论】:

    • 非常感谢,它有效:) 如果我想检索所有目的地(这里:波尔图、法鲁、里约热内卢和布宜诺斯艾利斯)以及相应的日期,我应该如何进行?我希望将结果显示在不同的列中(city_1:porto、date_1:2020-05-28 11:51:25.201864、city_2:faro、date_2:2020-06-06 23:10:06.878539 等)再次非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2016-11-13
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    • 2016-06-24
    • 1970-01-01
    • 2013-06-22
    • 1970-01-01
    相关资源
    最近更新 更多