Reputation: 107
I'm trying to expand an array of object in JSON with PostgreSQL.
TABLE CONTACTS (id int, data json);
1, {'firstName': 'John', 'lastName': 'Doe', 'addresses': [{'street': '1 Heaven St.', city: 'Wonderland'}, {'street': '3 Hell St.', city: 'Scarycity'}] }
2, {'firstName': 'Shiv', 'lastName': 'Durham', 'addresses': [{'street': '1 Sugar St.', city: 'Sweet City'}] }
And I want to turn it into view as
contact_id|address |
1 |{'street': '1 Heaven St.', city: 'Wonderland'} |
1 |{'street': '3 Hell St.', city: 'Scarycity'} |
2 |{'street': '1 Sugar St.', city: 'Sweet City'} |
I tried some native function but i failed to get wanted result.
Upvotes: 2
Views: 111
Reputation: 15624
select
id as contact_id,
json_array_elements(data->'addresses') as address
from contacts;
Upvotes: 1