1

I have a string coldata->>'f1' which I need to send dynamically to fetch JSON object.

What I want exactly is:

RAISE NOTICE 'OBJECT %', fc_data->'firstname'->>'value';

In my case I am getting the firstname dynamically in the variable coldata->>'f1' in my stored procedure. I need to send the key dynamically to get the value. For which I tried the below code:

RAISE NOTICE 'OBJECT %', ((('fc_data->')::text) || '''' || ((coldata->>'f1')::text) || '''');

Which is displaying fc_data1->'firstname', this is being considered as string by Postgres and I want the value of it. So I tried converting it into jsonb as below:

RAISE NOTICE 'OBJECT %', ((('fc_data->')::text) || '''' || ((coldata->>'f1')::text) || '''')::jsonb;

It is giving me the below error:

ERROR:  invalid input syntax for type json
DETAIL:  Token "fc_data" is invalid.

How do I concatenate the string as key to the object?

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
Sai sri
  • 515
  • 12
  • 25

1 Answers1

0

The -> operator for json / jsonb takes text or int to the right, which can come from an expression. You can simply:

DO
$do$
DECLARE
   coldata jsonb := '{"f1":"firstname"}';
   fc_data jsonb := '{"firstname": {"value":123}}';
BEGIN
   RAISE EXCEPTION 'OBJECT %', fc_data -> (coldata->>'f1') ->> 'value';
END
$do$;

db<>fiddle here (I made it an exception in the fiddle, wo we get to see it.)

Just to add parentheses like demonstrated.

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228