如何将Json数据导入Postgres表

时间:2018-06-28 03:00:28

标签: php json postgresql

我有一个API,可提供名为 corporateHoliday.txt 的json数据文本文件。

数据如下:

{
    "holiday_id":"1712010100000104",
    "holiday_date":"2018-12-30 00:00:00.0",
    "holiday_description":"SUNDAY",
    "holiday_status":"A"
},
{
    "holiday_id":"1712010100000103",
    "holiday_date":"2018-12-29 00:00:00.0",
    "holiday_description":"SATURDAY",
    "holiday_status":"A"
}

我的postgres表属性如下所示: t_leave_holida(objectid,holiday_date,description,recstatus)

我想将这些json数据从txt文件导入到postgres数据库表中吗?

2 个答案:

答案 0 :(得分:0)

您可以使用jsonb类型,只需从json中选择数据即可,例如:

db=# create table t_leave_holida(objectid bigint, holiday_date timestamp(1), description text,recstatus text);
db=# insert into t_leave_holida select (d->>'holiday_id')::bigint, (d->>'holiday_date')::timestamp, d->>'holiday_description', d->>'holiday_status' from (select '{
    "holiday_id":"1712010100000104",
    "holiday_date":"2018-12-30 00:00:00.0",
    "holiday_description":"SUNDAY",
    "holiday_status":"A"
}'::jsonb d) ali;
INSERT 0 1
db=# select * from t_leave_holida;
     objectid     |    holiday_date     | description | recstatus
------------------+---------------------+-------------+-----------
 1712010100000104 | 2018-12-30 00:00:00 | SUNDAY      | A
(1 row)

答案 1 :(得分:0)

构造一个json数组,我们可以将所有记录插入t_leave_holida

  insert into t_leave_holida(objectid, holiday_date,description,recstatus)
  select holiday_id,holiday_date,holiday_description,holiday_status from
  json_to_recordset(
   '[
      {
        "holiday_id":"1712010100000104",
        "holiday_date":"2018-12-30 00:00:00.0",
        "holiday_description":"SUNDAY",
        "holiday_status":"A"
      },
      {
        "holiday_id":"1712010100000103",
        "holiday_date":"2018-12-29 00:00:00.0",
        "holiday_description":"SATURDAY",
        "holiday_status":"A"
      }
    ]'
  ) as x(holiday_id bigint, holiday_date date, holiday_description text,holiday_status text);