0

I have a JSONB field value:

{
   "status":200,
   "response":{
      "page":1,
      "limit":10,
      "total":4,
      "orders":[
         {
            "id":40201
         },
         {
            "id":40111
         }
      ]
   }
}

How do I query for the orders array object with id=40201?

Im trying to query for all rows with response->orders->[id: 40201]

2
  • The "orders array" is simply the_column -> 'response' -> 'orders' not sure what you mean with "orders array with id = ..." there are multiple IDs in the array. What exactly is the output you want? Commented Jul 19, 2019 at 15:40
  • Im trying to query for all rows with response->orders->[id: 40201] Commented Jul 19, 2019 at 15:42

2 Answers 2

1

demo:db<>fiddle

If you know that this is the first object in your array (zero-based!):

SELECT
    yourjson -> 'response' -> 'orders' -> 0

If not, you have to expand your array into one row per element with jsonb_array_elements() and filter each row:

SELECT 
    elems.value
FROM 
    yourtable,
    jsonb_array_elements(yourjson -> 'response' -> 'orders') elems
WHERE
    elems ->> 'id' = '40201'

documentation

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

2 Comments

just to clarify, Im trying to query for all rows with response->orders->[id: 40201]
@Hackbyrd Then you'll need the second way: dbfiddle.uk/…
1

I would use an exists query for that:

select *
from the_table
where exists (select *
              from jsonb_array_elements(the_json_column -> 'response' -> 'orders') as x (o)
              where x.o ->> 'id' = 40201');

alternatively with the @> contains operator:

select *
from the_table
where exists (select *
              from jsonb_array_elements(the_json_column -> 'response' -> 'orders') as x (o)
              where x.o @> '{"id" : 40201}';

Comments

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.