2

I have JSON stored in a jsonb column:

[
  {
    "ORDER_TYPE": "foo",
    "PAYMENT_TYPE": "VISA",
  }
]

I can query fine but is it possible to select specific parts (PAYMENT_TYPE) of the json from the resultset?

SELECT PAYMENT_TYPE 
FROM tools.orders 
WHERE responsejsonb::jsonb @> '[{"ORDER_TYPE":"foo"}]';

Desired output "PAYMENT_TYPE": "VISA" or "VISA"

0

2 Answers 2

4

Flatten the JSONB array first.

select j ->> 'PAYMENT_TYPE' as payment_type -- and other expressions?
from tools.orders
cross join lateral jsonb_array_elements(responsejsonb::jsonb) as l(j)
where j ->> 'ORDER_TYPE' = 'foo';

Edit
If however the responsejsonb array has only one element (or only the first one matters) then it's simpler, the expression that you need is responsejsonb::jsonb->0->>'PAYMENT_TYPE'.

SELECT responsejsonb::jsonb->0->>'PAYMENT_TYPE'
FROM tools.orders 
WHERE responsejsonb::jsonb @> '[{"ORDER_TYPE":"foo"}]';
Sign up to request clarification or add additional context in comments.

1 Comment

@LaurenzAlbe Is its implementation faster or is it a matter of taste? j @> '{"ORDER_TYPE": "foo"}'?
2

You can use a JSON path expression:

SELECT jsonb_path_query_first(responsejsonb, '$[*] ? (@.ORDER_TYPE == "foo").PAYMENT_TYPE')
FROM tools.orders 
WHERE responsejsonb @> '[{"ORDER_TYPE":"foo"}]';

If you want all payment types, use jsonb_path_query_array() instead.

Online example


If responsejsonb is really defined with the jsonb type, the cast to jsonb is useless.

5 Comments

I get this error when trying this: function jsonb_path_query_first(jsonb, unknown) does not exist
@IlyasPatel: works for me maybe you are using an older Postgres version
PostgreSQL 11.13 on x86_64-pc-linux-gnu, compiled by x86_64-pc-linux-gnu-gcc (GCC) 7.4.0, 64-bit
this is the version I am using.
Amazon RDS - in AWS

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.