Being a novice to Postgres and SQL in general, I have the following scenario in Postgres 9.6:
table1
"Myjson" JSON
"DateOfAcquisition" DATE
"Id" INT
In "Myjson"
there is a list which I iterate trough with a FOR
loop.
My objective is to place the elements of each json list in table1
in another table:
table2
jsonelem1 INT
jsonelem2 INT
"DateOfAcquisition" DATE
"Id" INT
I have written the following code for parsing the json field but I am not sure how to run the for
loop for each record of the first table.
DO
$BODY$
DECLARE
omgjson json := myjsonfield; -- this should change for every row of the first table
i json;
myJsonelem1 INT;
myJsonelem2 INT;
begin
FOR i IN SELECT * FROM json_array_elements(omgjson)
loop
myJsonelem2 i->> 'jsonsubfield'::INT;
INSERT INTO destinationTable VALUES (myJsonelem2,DateOfAcquisition);
END LOOP;
END;
$BODY$ language plpgsql