2

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?

1 Answer 1

3

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

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks once again. Just to note for anyone else struggling with bgutil, it's not currently (Jan 2021) available outside the US as a public dataset, it needs to be deployed, github.com/GoogleCloudPlatform/bigquery-utils/issues/252

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.