如何将对象的JSON数组作为单独的元素插入PostgreSQL

时间:2019-05-30 08:14:19

标签: sql postgresql

我有JSON,并将其发送到postgresql函数。我需要将weekDays数组内的每个对象插入单独的行中,并将对象内的每个键插入单独的列中,并且它需要包括weekId

我的桌子看起来像这样: enter image description here

{
   "weekId":20,
   "weekDays":[
      {
         "day_of_week":"Monday",
         "working_hours":22.5,
         "description":"text",
         "date":"May 22, 2019"
      },
      {
         "day_of_week":"Tuesday",
         "working_hours":22.5,
         "description":"text",
         "date":"May 22, 2019"
      }
   ]
} 

那么最好的方法是什么?我可以做这样的事情:

INSERT INTO timesheet(day_of_week, working_hours, description, date)
SELECT day_of_week, working_hours, description, date
FROM json_to_recordset(weeks_days)
AS x(day_of_week varchar, working_hours REAL, description text, date timestamp);

但是如何包含不在数组中的weekId

1 个答案:

答案 0 :(得分:1)

使用->>运算符获取weekId作为文本并将其转换为整数,例如:

WITH my_data(jsonb_column) AS (
VALUES
('{
   "weekId":20,
   "weekDays":[
      {
         "day_of_week":"Monday",
         "working_hours":22.5,
         "description":"text",
         "date":"May 22, 2019"
      },
      {
         "day_of_week":"Tuesday",
         "working_hours":22.5,
         "description":"text",
         "date":"May 22, 2019"
      }
   ]
}'::jsonb)
)

INSERT INTO timesheet(weekid, day_of_week, working_hours, description, date)
SELECT (jsonb_column->>'weekId')::int, day_of_week, working_hours, description, date
FROM my_data
CROSS JOIN jsonb_to_recordset(jsonb_column->'weekDays')
AS x(day_of_week varchar, working_hours REAL, description text, date timestamp)
RETURNING *;

 id | weekid | day_of_week | working_hours | description |        date         
----+--------+-------------+---------------+-------------+---------------------
  1 |     20 | Monday      |          22.5 | text        | 2019-05-22 00:00:00
  2 |     20 | Tuesday     |          22.5 | text        | 2019-05-22 00:00:00
(2 rows)

在Postgres 11中,您可以将jsonb数字转换为整数(->而不是->>):

SELECT (jsonb_column->'weekId')::int, day_of_week, working_hours, description, date