Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ERROR : cannot call jsonb_to_recordset on a non-array (postgresql)

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)
like image 281
muhammad ahmad falak Avatar asked Jun 22 '26 00:06

muhammad ahmad falak


2 Answers

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>
like image 65
Barbaros Özhan Avatar answered Jun 24 '26 13:06

Barbaros Özhan


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)
like image 27
Bergi Avatar answered Jun 24 '26 13:06

Bergi