如何将json对象转换为postgres表

时间:2019-10-04 04:32:03

标签: sql json postgresql

我正在尝试将大量数据插入postgres。因此,我已经将数据转换为json对象,现在我想将该数据插入到物理表中,json对象可以包含超过10万条记录。所以我想通过使用postgres函数动态地做到这一点。我的问题是如何以表格形式查询示例数据

这是示例json数据

[
  {
    "sequence": 123123.0,
    "Card number ": "12312qwe",
    "Tracking number": 1231233.0,
    "Expiry Date": 43741.0
  },
  {
    "sequence": 123123.0,
    "Card number ": "12312qwe",
    "Tracking number": 1231233.0,
    "Expiry Date": 43741.0
  },
 {
    "sequence": 123123.0,
    "Card number ": "12312qwe",
    "Tracking number": 1231233.0,
    "Expiry Date": 43741.0
  }
]

1 个答案:

答案 0 :(得分:1)

您可以使用tab列(例如json)和json_array_elements()函数来创建表(例如jsondata):

create table tab as
with tab as
(
 select '[
  {
    "sequence": 123123.0,
    "Card number ": "12312qwe",
    "Tracking number": 1231233.0,
    "Expiry Date": 43741.0
  },
  {
    "sequence": 123123.0,
    "Card number ": "12312qwe",
    "Tracking number": 1231233.0,
    "Expiry Date": 43741.0
  },
 {
    "sequence": 123123.0,
    "Card number ": "12312qwe",
    "Tracking number": 1231233.0,
    "Expiry Date": 43741.0
  }
]'::json as jsondata
)
select js ->> 'sequence' as sequence, js ->> 'Card number ' as Cardnumber, 
       js ->> 'Tracking number' as Trackingnumber, js ->> 'Expiry Date' as ExpiryDate
  from
  (
    select json_array_elements(jsondata) as js
      from tab
  ) q1 

Demo