5

I have a column open_houses that's JSON data type and it looks like this:

open_houses
[{"Date": "2017-08-13", "ToTime": "4:00PM", "FromTime": "2:00PM"}]
[{"Date": "2017-08-12", "ToTime": "3:00PM", "FromTime": "1:00PM"}]
[{"Date": "2017-08-12", "ToTime": "4:00PM", "FromTime": "2:00PM"}]
[{"Date": "2017-08-13", "ToTime": "3:00PM", "FromTime": "1:00PM"}]

When I try to extract 'Date' from this column I get an error -

SELECT ...
FROM   prod.vw_listing
WHERE  ...
       ...
       AND open_houses[1] -> 'Date'::DATE >= current_date;

Error:

cannot subscript type jsonb because it is not an array

3 Answers 3

8

Use the -> operand to get a json array element:

with vw_listing (open_houses) as ( values 
    ('[{"Date": "2017-08-13", "ToTime": "4:00PM", "FromTime": "2:00PM"}]'::jsonb),
    ('[{"Date": "2017-08-12", "ToTime": "3:00PM", "FromTime": "1:00PM"}]'),
    ('[{"Date": "2017-08-12", "ToTime": "4:00PM", "FromTime": "2:00PM"}]'),
    ('[{"Date": "2017-08-13", "ToTime": "3:00PM", "FromTime": "1:00PM"}]')
)
select (open_houses -> 0 ->> 'Date')::date
from vw_listing
;
    date    
------------
 2017-08-13
 2017-08-12
 2017-08-12
 2017-08-13
Sign up to request clarification or add additional context in comments.

Comments

5

I was able to resolve this by doing this:

SELECT ...

FROM   prod.vw_listing
WHERE  ...
       AND (open_houses -> 0 ->> 'Date')::date>= current_date;

Comments

0

Also you can use this select:

select (open_houses#>> '{0, Date}')::date

It is equeal to selecting element like open_houses[0]['Date']

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.