14
create table test(a json);

insert into test(a) 
values('{"orders":[{"orderId":1}, {"orderId":2, "status":"done"}, {"orderId":3}]}');

Given the structure above, can I get an array or set of orderIds that are not 'done'? And by that, I mean can I get the orderIds from with sql or plpgsql?

Any advice would be great! Thank you very much!

1
  • That's not valid JSON, did you actually try inserting it? (edit: fixed it, but seriously, test your examples). Commented Jun 10, 2014 at 2:02

1 Answer 1

25

Once I fixed the broken JSON, this was just a LATERAL query to unpack the array and filter it.

select (x->>'orderId')::integer
from test,
     json_array_elements(a->'orders') x 
where (x ->> 'status') IS DISTINCT FROM 'done';

I used IS DISTINCT FROM so I didn't have to test for both NULL (no key) and != 'done'.

Sign up to request clarification or add additional context in comments.

1 Comment

For anyone else running into the problem, you'll need to use jsonb_array_elements on a jsonb datatype (note the extra B).

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.