I have a table kind of like this, let's call it base_table:
id | date | json_array
---+-------------+------------------
1 2018-01-01 [{..a..},{..b..}]
2 2018-01-01 [{..c..}]
3 2018-01-01 [{..d..}]
4 2018-01-01 [{..e..},{..f..}]
. . .
. . .
. . .
The json_array column always has either 1 or 2 elements.
I need to make a select in SQL where on each line I can show: the respective id from base_table; its order (if the element comes 1st or 2nd inside the array); the element of the json_array.
The output should be something like this:
id | order | json_object
---+-------+------------
1 1 {..a..}
1 2 {..b..}
2 1 {..c..}
3 1 {..d..}
4 1 {..e..}
4 2 {..f..}
. . .
. . .
. . .
But I'm having a lot of trouble with showing the order of the elements... Can anyone help?
The database is in PostgreSQL 9.6.1
Use json_array_elements(json_array) with ordinality
:
with my_table(id, json_array) as (
values
(1, '[{"a": 1}, {"b": 2}]'::json),
(2, '[{"c": 3}]'),
(3, '[{"d": 4}]'),
(4, '[{"e": 5}, {"f": 6}]')
)
select id, ordinality, value
from my_table
cross join json_array_elements(json_array) with ordinality;
id | ordinality | value
----+------------+----------
1 | 1 | {"a": 1}
1 | 2 | {"b": 2}
2 | 1 | {"c": 3}
3 | 1 | {"d": 4}
4 | 1 | {"e": 5}
4 | 2 | {"f": 6}
(6 rows)
DbFiddle.
Read 7.2.1.4. Table Functions in the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With