Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access json objects using variables as keys in postgresql

I have a json poll_result

{"total_votes":1,"yes":1,"no":0}

and I have a variable that has the key

vote_to = _poll_response::json#>>'{vote}';

and that returns the "yes".

Now I want to access poll_result json based on the vote_to variable's value, so I am trying

raise notice '%',poll_result::json#>>'{||vote_to||}';

but this is printing <NULL>. Even I have tried like

raise notice '%,%',poll_result,poll_result::json#>>'{''||vote_to||''}';

but the result is same <NULL>.

Please help!!!

like image 508
Sunil Garg Avatar asked May 10 '26 01:05

Sunil Garg


1 Answers

See the example on how to use a variable with ->> and #>> operators:

do $$
declare
    pool_result json = '{"total_votes":1,"yes":1,"no":0}';
    vote_to text = 'yes';
begin
    raise notice 'yes: %', pool_result ->> vote_to;
    -- or
    raise notice 'yes: %', pool_result #>> array[vote_to]; 
end;
$$

NOTICE:  yes: 1
NOTICE:  yes: 1

If the the value of the variable is in double quotes you should trim them:

do $$
declare
    pool_result json = '{"total_votes":1,"yes":1,"no":0}';
    vote_to text = '"yes"';
begin
    raise notice 'yes: %', pool_result ->> trim(vote_to, '"');
    -- or
    raise notice 'yes: %', pool_result #>> array[trim(vote_to, '"')]; 
end;
$$
like image 96
klin Avatar answered May 11 '26 15:05

klin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!