2

Is it possible to do something like this in Postgres:

do $$
declare
  v_key text;
  v_json jsonb;
begin
  v_key := 'id';
  v_json := jsonb_build_object(
    'id', jsonb_build_object('nest_id',1)
  );
  raise notice '%', v_json #> '{'||v_key||'}'->>'nest_id';
end$$

ERROR: operator does not exist: jsonb #> text
No operator matches the given name and argument type(s). You might need to add explicit type casts.

1
  • 1
    '{'||v_key||'}'::jsonb Commented Sep 7, 2016 at 10:17

1 Answer 1

1

Right operand type of the operator #> is text array. Use array[...] notation:

raise notice '%', v_json #> array[v_key] ->> 'nest_id';

or explicitly cast a formatted array literal:

raise notice '%', v_json #> ('{'||v_key||'}')::text[] ->> 'nest_id';
-- or nicer
raise notice '%', v_json #> format('{%s}', v_key)::text[] ->> 'nest_id';
Sign up to request clarification or add additional context in comments.

Comments

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.