0
DO
$$
DECLARE
array_ json;
category_name text;
category_ json:='{"Maincategory":"Vehicle","Categoryname":"Car"}'::json;
BEGIN
category_name:=(SELECT category_  ->'Maincategory'::text) ;
array_:=(SELECT elements -> category_name FROM webuser.footable WHERE id=somenumber)::json;
raise notice '%',array_ ;
END
$$;


                             elements                       
                              (json)                    
|-------------------------------------------------------------------------------------|
|{"Vehicle": [{"Car": 3}, {"Truck": 1}], "Office": [{"Printer": 3}, {"Desk": 8}]}     |

I have elements column and i want to retrieve vehicle array which is ([{"Car": 3}, {"Truck": 1}] ) that will be stored in array_ variable. I get array_ always null. What is wrong with this code?

1 Answer 1

1

category_ ->'Maincategory'::text will return "Vehicle", while you need the value of the filed...

change (SELECT category_ ->'Maincategory'::text)

to

(SELECT category_ ->>'Maincategory'::text), like here:

b=# DO
b-# $$
b$# DECLARE
b$# array_ json;
b$# category_name text;
b$# category_ json:='{"Maincategory":"Vehicle","Categoryname":"Car"}'::json;
b$# elements  json:= '{"Vehicle": [{"Car": 3}, {"Truck": 1}], "Office": [{"Printer": 3}, {"Desk": 8}]}';
b$# BEGIN
b$# category_name:=(SELECT category_ ->>'Maincategory'::text) ;
b$# raise info '%',(select elements->category_name);
b$# --array_:=(SELECT elements -> category_name FROM webuser.footable WHERE id=somenumber)::json;
b$# --raise notice '%',array_ ;
b$# END
b$# $$;
INFO:  [{"Car": 3}, {"Truck": 1}]
DO
Sign up to request clarification or add additional context in comments.

2 Comments

that works but if i use a variable(in that case : category_name) instead of 'Vehicle' than it doesnt work.
@sommeguyy I updated the answer - mind -> is different from ->>

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.