简体   繁体   中英

Bigquery - json_array extract and count elements from a nested arrays

I have a JSON field my table which looks like this. There could be any number of menu categories and any number of items

{
"menu": {
    "salad": [
        {
            "item": "russian salad"
        },
        {
            "item": "french salad"
        }
    ],
    "soups": [
        {
            "item": "french soup"
        },
        {
            "item": "english soup"
        },
        {
            "item": "english soup"
        }
    ]
}

There could be any number of menu category (salad, soup) plus any number of items within each category

salad | 2
soups | 3

I've looked at my own previous question , but unsure how I can modify to accommodate for any number of categories and items?

Consider below approach

select key, array_length(split(values)) items
from `project.dataset.table`,
unnest(`bqutil.fn.json_extract_keys`(json_extract(col, '$.menu'))) key with offset 
join unnest(`bqutil.fn.json_extract_values`(json_extract(col, '$.menu'))) values with offset 
using(offset)          

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