【问题标题】:How to import this JSON data into a postgresql table?如何将此 JSON 数据导入 postgresql 表?
【发布时间】:2021-10-08 05:18:34
【问题描述】:

我有以下 JSON:

{
   "ticket":{
      "ticket":"61086762bb68d90001148fe9",
      "timestamp":"2021-08-02T18:45:06.581-0300"
   },
   "serie":{
      "measurement":{
         "nemo":"RT",
         "description":"Real Time"
      },
      "tagSet":{
         "Granularity":"1h",
         "Facility":"382"
      },
      "fieldSet":{
         "EnvTemperature":"°C",
         "HorizIrrad":"W/m²"
      }
   },
   "values":[
      {
         "tagSet":{
            "Facility":"382",
            "Granularity":"1h"
         },
         "fieldSet":{
            "EnvTemperature":7.0,
            "HorizIrrad":632.0
         },
         "time":"2021-08-02T11:00:00.000-0300"
      },
      {
         "tagSet":{
            "Facility":"382",
            "Granularity":"1h"
         },
         "fieldSet":{
            "EnvTemperature":10.0,
            "HorizIrrad":884.0
         },
         "time":"2021-08-02T12:00:00.000-0300"
      }
   ]
}

我想知道如何将“值”部分中的“EnvTemperature”、“HorizIrrad”和“时间”导入如下表格:

time EnvTemperature HorizIrrad
2021-08-02 11:00:00 7 632
2021-08-02 12:00:00 10 884

或者像这样:

time Fieldset value
2021-08-02 11:00:00 EnvTemperature 7
2021-08-02 11:00:00 HorizIrrad 632
2021-08-02 12:00:00 EnvTemperature 10
2021-08-02 12:00:00 HorizIrrad 884

【问题讨论】:

    标签: json postgresql import jsonb postgresql-13


    【解决方案1】:

    使用函数jsonb_array_elements(jsonb)将所有json数组元素返回为value。

    select 
        (value->>'time')::timestamp as "time",
        (value->'fieldSet'->>'EnvTemperature')::numeric as "EnvTemperature",
        (value->'fieldSet'->>'HorizIrrad')::numeric as "HorizIrrad"
    from the_data
    cross join jsonb_array_elements(json_col->'values')
    

    在Db<>fiddle.中测试它

    阅读JSON Functions and Operators.

    【讨论】:

      猜你喜欢
      • 2017-07-17
      • 1970-01-01
      • 1970-01-01
      • 2017-01-06
      • 1970-01-01
      • 2011-03-27
      • 1970-01-01
      • 2018-09-20
      • 2017-07-12
      相关资源
      最近更新 更多