简体   繁体   中英

Unnest a JSON array in as multiple rows - BigQuery

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?

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM