【问题标题】:Convert a json which is a list of dictionaries into column/row format in Postgresql将作为字典列表的 json 转换为 Postgresql 中的列/行格式
【发布时间】:2020-12-30 09:55:22
【问题描述】:

我有一个 json,它是一个字典列表,语法如下:

 [ 
     {
    "Date_and_Time": "Dec 29, 2017 15:35:37",
    "Componente": "Bar",
    "IP_Origen": "175.11.13.6",
    "IP_Destino": "81.18.119.864",
    "Country": "Brazil",
    "Age": "3"

},

{

    "Date_and_Time": "Dec 31, 2017 17:35:37",
    "Componente": "Foo",
    "IP_Origen": "176.11.13.6",
    "IP_Destino": "80.18.119.864",
    "Country": "France",
     'Id': '123456',
     'Car': 'Ferrari'

},
{
  "Date_and_Time": "Dec 31, 2017 17:35:37",
    "Age": "1",
    "Country": "France",
     'Id': '123456',
     'Car': 'Ferrari'
},
{
    "Date_and_Time": "Mar 31, 2018 14:35:37",
    "Componente": "Foo",
    "Country": "Germany",
     'Id': '2468',
     'Genre': 'Male'

}
]

json 非常大,每个字典都有不同数量的键/值字段。我想要做的是在 postgresSQL 中创建一个表,其中键代表一列,值代表一行。在上面解释的示例中,我想要这样的表格:

Date_and_Time          | Componente | IP_Origen   | IP_Destino    | Country| Id    | Car    | Age| Genre
         
Dec 29, 2017 15:35:37  | Bar        | 175.11.13.6 | 81.18.119.864 | Brazil |  -    |   -    | 3  | -
Dec 31, 2017 17:35:37  | Foo        | 176.11.13.6 | 80.18.119.864 | France |123456 |Ferrari | -  | -
Dec 31, 2017 17:35:37  | -          | -           |   -           | France |123456 |Ferrari | 1  | -
Mar 31, 2018 14:35:37  | Foo        |   -         |    -          | Germany| 2468  |    -   | -  | Male

我能想到的唯一解决方案是将值逐个放置,但这根本没有效率

【问题讨论】:

    标签: sql json postgresql sql-insert


    【解决方案1】:

    您可以使用jsonb_to_recordset 从您的json 创建记录集,然后使用insert into 插入记录。

    insert into table
    select * from jsonb_to_recordset('<your json>'::jsonb)
    as rec(Date_and_Time datetime, Componente text, IP_Origen text) --Specify all columns inside the table
    

    Sample DBFiddle

    【讨论】:

    • 当你说 ` '' ` 你的意思是,整个 json 或只有一个字典
    • 整个 json 数组。检查 DBFiddle 以获取示例 json。
    猜你喜欢
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-26
    • 1970-01-01
    • 2019-02-10
    • 2017-04-23
    • 2021-10-13
    相关资源
    最近更新 更多