1

I have a JSONB column with values in following JSON structure

{
  "a": "value1", "b": [{"b1": "value2", "b3": "value4"}, {"b1": "value5", "b3": "value6"}]
}

I need to select only b1 field in the result. So expected result would be

["value2", "value5"]

I can select complete array using query

select columnname->>'b' from tablename

2 Answers 2

1

step-by-step demo:db<>fiddle

SELECT
    jsonb_agg(elements -> 'b1')                       -- 2
FROM mytable,
    jsonb_array_elements(mydata -> 'b') as elements   -- 1
  1. a) get the JSON array from the b element (b) extract the array elements into one row each
  2. a) get the b1 values from the array elements (b) reaggregate these values into a new JSON array
Sign up to request clarification or add additional context in comments.

Comments

1

If you are using Postgres 12 or later, you an use a JSON path query:

select jsonb_path_query_array(the_column, '$.b[*].b1')
from the_table;

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.