sidgate
sidgate

Reputation: 15244

How to select single field from array of json objects?

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

Upvotes: 1

Views: 1608

Answers (2)

user330315
user330315

Reputation:

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;

Upvotes: 1

S-Man
S-Man

Reputation: 23686

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

Upvotes: 1

Related Questions