1

Below is my stored procedure which I am trying to create. I am converting the table data into json and loop the JSON which I have created. But I am facing issue while doing so.

CREATE OR REPLACE FUNCTION file_compare()

    RETURNS text
    LANGUAGE 'plpgsql'

    COST 100
    VOLATILE 
    AS $BODY$
    declare 
    fpo_data jsonb;
    loopupto INTEGER := 0;

    begin

    select  json_agg(("fpdata"))::jsonb
    FROM (
      SELECT "fo_data" as fpdata
     from fpo
    limit 100
    ) t  INTO "fpo_data";

    FOR i IN "fpo_data"
  LOOP
    RAISE NOTICE 'output from space %', i;
  END LOOP;


    return fpo_data;
    end;
$BODY$;

I am getting the below error

 ERROR:  syntax error at or near ""fpo_data""
 LINE 27:  FOR i IN "fpo_data"

What is the issue? Please help!!

3
  • Please provide a data sample and the expected result, otherwise there is no way we can tell if your function makes sense. Btw, you're trying iterate over a json record. Is it supposed to be an array? Commented Jan 24, 2020 at 13:41
  • @JimJones That is a complex one . But I need to get all the data in "fo_data" in a json format and loop it Commented Jan 24, 2020 at 13:50
  • I hope that your code is not indented like it is in the question. Commented Jan 24, 2020 at 14:30

1 Answer 1

1

You forgot to declare i, there are a few useless " and you're trying to iterate over a jsonb variable.

Assuming that fpo_data has a jsonb array stored, try this:

CREATE OR REPLACE FUNCTION file_compare()
RETURNS TEXT LANGUAGE 'plpgsql' COST 100 VOLATILE AS $BODY$
DECLARE
  fpo_data jsonb;
  i JSONB;
BEGIN
  SELECT json_agg((fpdata))::jsonb
  FROM (SELECT fo_data AS fpdata
        FROM fpo LIMIT 100
    ) t  INTO fpo_data; 
  FOR i IN SELECT * FROM jsonb_array_elements(fpo_data) LOOP
    RAISE NOTICE 'output from space %', i;
  END LOOP;
  RETURN fpo_data;
END;
$BODY$;

Edit: To retrieve only the element bene_first_name in the raise notice statement just do:

RAISE NOTICE 'output from space %', (i->>0)::JSONB->'bene_first_name';
Sign up to request clarification or add additional context in comments.

2 Comments

I am getting fpo_data as below in return. If i try to print 'bene_firstname' like this RAISE NOTICE 'output from space %', i->>'bene_firstname' I am getting the error as ERROR: operator does not exist: record ->> unknown. How to I get 'bene_firstname' from the below json array ["{\"bene_first_name\":{\"value\":\"Chris\"},\"bene_last_name\":{\"value\":\"Ronald\"}}", "{\"bene_first_name\":{\"value\":\"John\"},\"bene_last_name\":{\"value\":\"Wick\"}}", "{\"bene_first_name\":{\"value\":\"James\"},\"bene_last_name\":{\"value\":\"Cooper\"}}"]
My postgres version is 10.11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.