B
B
BoneFletcher2020-10-29 15:36:26
PostgreSQL
BoneFletcher, 2020-10-29 15:36:26

How to implement map/array_walk on PostgreSQL?

The task is this.
[{"a": 1, "b": 2}, {"a": 10, "b": 20}]
It is necessary to turn such JSON into
[1, 10]
such for each element of the array, extract the value with the key "a".
In JS/PHP this can be done in one line by converting the array elements. How can this be done in PostgreSQL?

While I was able to reach such a request
select jsonb_array_elements(my_column)->>'a'

. It returns a set of the necessary values, but in the form of several lines. And you need to get them in the form of a single array.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
galaxy, 2020-10-29
@BoneFletcher

Well assemble back into an array

select array_agg(v)
  from (select jsonb_array_elements(col)->'a' v
    from (values ('[{"a": 1, "b": 2}, {"a": 10, "b": 20}]'::jsonb)) as t(col)
  ) t1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question