2

I was trying to read elements from Json array inside another array that is stored on Postgres database, but my result set was always empty. My table looks like below: enter image description here

Sample Json from table:

{"test":{"accountName":"OS1U","details":[{"status":{"statusCode":"Test Ready","modifiedDate":"2023年07月31日T14:53:49Z"},"products":[{"productId":"0001","productName":"2GB","productDescription":"testproduct12"},{"productId":"0005","productName":"2GB","productDescription":"testproduct12"}]}]}}

Here my requirement is to get all the id's from table which is having productId (0001,0005). I tried below sql:

SELECT x.id 
FROM (
 SELECT json_array_elements("json" -> 'test' -> 'details'->'products') AS products,"id"
 FROM table_test b
 
 ) x
WHERE x.products ->> 'productId' in ('0001','0005');

But it always returns empty dataset. Can anyone please guide me to correct the above statement

asked Jul 31, 2023 at 17:14

1 Answer 1

0

The problem is that both details and products are arrays.

If you store it as jsonb then you can use jsonb_path_exists much more efficiently

SELECT t.id
FROM table_test t
WHERE jsonb_path_exists(t.json, '
 $.test.details[*].products[*].productId ? (@ == "0001" || @ == "0005")
 ');

db<>fiddle

Otherwise you need to do a series of json_array_element calls to unwrap each array.

SELECT t.id
FROM table_test t
WHERE EXISTS (SELECT 1
 FROM json_array_elements(t.json -> 'test' -> 'details') j1
 CROSS JOIN json_array_elements(j1 -> 'products') j2
 WHERE j2 ->> 'productId' IN ('0001', '0005')
);

db<>fiddle

answered Aug 1, 2023 at 0:15
1
  • Thanks , It works now Commented Aug 1, 2023 at 4:33

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.