in column steps i have json values like [{"id":"ali","status":"open","reminder":"tomorrow","show_due_date":"true"}]
and i want to query new table like separate column for each key
id | status| reminder | show_due_date
i wrote this script but getting error of cannot call jsonb_to_recordset on a non-array
WITH series (jsonbrecords) AS (Select steps::jsonb from files)
INSERT INTO new
(column1,
column2,
column3,
column4)
SELECT t."id", t."status", t."reminder", t."show_due_date"
FROM series
CROSS JOIN LATERAL
jsonb_array_elements(jsonbrecords) AS x(doc),
jsonb_to_recordset(x.doc) as t("id" text, "status" text,"reminder" text,"show_due_date" text)
You can bring each respective columns using the below query without need of the other function :
SELECT x.doc ->> 'id' AS id,
x.doc ->> 'status' AS status,
x.doc ->> 'reminder' AS reminder,
x.doc ->> 'show_due_date' AS show_due_date
FROM series
CROSS JOIN LATERAL jsonb_array_elements(jsonbrecords) AS x(doc)
Demo
You can go on with this query to insert into a new table if you wish :
INSERT INTO new_table(column1,column2,column3,column4)
<the above query>
You're unnesting the json array twice, once with jsonb_array_elements and once with jsonb_to_recordset. You need only one of them, e.g.
INSERT INTO new(column1, column2, column3, column4)
SELECT t."id", t."status", t."reminder", t."show_due_date"
FROM files f
CROSS JOIN LATERAL jsonb_to_recordset(f.steps::jsonb) AS t("id" text, "status" text, "reminder" text, "show_due_date" text)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With