patternsqlModerate
Extract JSON array of numbers from JSON array of objects
Viewed 0 times
objectsarraynumbersextractjsonfrom
Problem
I have a table containing a json array of objects similar to this:
I would like to get a table containing a json array of only, say, the "a" values:
I use PostgreSQL 11, so the latest functions are acceptable.
id | record
____________________
name1 | [{"a":0, "b":x}, {"a":1, "b":y}, {"a":2, "b":z}, ...]I would like to get a table containing a json array of only, say, the "a" values:
id | record
____________________
name1 | [0, 1, 2, ...]I use PostgreSQL 11, so the latest functions are acceptable.
Solution
You need to first unnest the array elements, and then aggregate back each value:
Online example: https://rextester.com/ZONHTW97204
select id,
(select jsonb_agg(t -> 'a') from jsonb_array_elements(record) as x(t)) as record
from the_table;Online example: https://rextester.com/ZONHTW97204
Code Snippets
select id,
(select jsonb_agg(t -> 'a') from jsonb_array_elements(record) as x(t)) as record
from the_table;Context
StackExchange Database Administrators Q#229069, answer score: 13
Revisions (0)
No revisions yet.