Reputation: 34376
I have a table that looks like this
| id | title | metadata |
| 1 | apples | [{"tags": [200,211], "categories": [313,412]}] |
| 2 | oranges | [{"tags": [311,112], "categories": [616,712]}] |
I want to unnest the metadata so the results is one row per tag
| id | title | tag |
| 1 | apples | 200 |
| 1 | apples | 212 |
| 2 | oranges | 313 |
| 2 | oranges | 112 |
I know I need to use JSON_EXTRACT_ARRAY to and UNNEST, but since there is another array nested inside JSON I'm a bit confused as to how these should interact?
Upvotes: 2
Views: 4050
Reputation: 173181
Consider below approach
select * except(metadata) from data,
unnest(split(trim(json_extract(trim(metadata, '[]'), '$.tags'), '[]'))) tag
if applied to sample data in your question - output is
Upvotes: 4