Skip to content
Advertisement

SQL procedure loop on a key from JSON object

I am trying to insert a JSON object into multiple tables

CREATE TABLE images
(
    id serial primary key ,
    image_url varchar(255),
    filename varchar(255)
);

Procedure:

CREATE OR REPLACE procedure example1(
    images_json json
)
AS
    $$
    DECLARE i json;
BEGIN
        RAISE NOTICE 'ITEM ID is %',images_json->>'item_id'; --will be used later on
    FOR i IN SELECT * FROM json_array_elements(images_json->>'images')
    LOOP
        INSERT INTO images (image_url, filename) VALUES (i->>'url', i->>'filename');
    end loop;
end;
    $$
    language plpgsql;

When I test it

call example1('{"item_id": 123,"images":[{ "url": "https://google.com","filename": "google.png"},
{ "url": "https://yahoo.com","filename":"yahoo.png"},
{"url": "https://www.bing.com","filename":"bing.png"}]}')

I get the following error

ERROR: function json_array_elements(text) does not exist

No function matches the given name and argument types. You might need to add explicit type casts.
Where: PL/pgSQL function example1(json) line 5 at FOR over SELECT rows

I want to insert each of the images array into images table.

Advertisement

Answer

Your immediate error is, that ->> returns a text value, but json_array_elements() expects a json value. You need to use the -> operator here:

FOR i IN SELECT * FROM json_array_elements(images_json -> 'images')
                                                        ^ here

But you don’t need a LOOP for this (or PL/pgSQL to begin with):

CREATE OR REPLACE procedure example1(images_json json)
AS
$$
BEGIN
  RAISE NOTICE 'ITEM ID is %',images_json->>'item_id'; --will be used later on
  INSERT INTO images (image_url, filename) 
  SELECT i->>'url', i->>'filename'
  FROM json_array_elements(images_json -> 'images') as i;
end;
$$
language plpgsql;
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement