I am trying to extract value from JSON ARRAY as below
with `project.dataset.table` as (
select '{"fruit":[{"apples":"5","oranges":"10","pear":"20"},
{"apples":"5","oranges":"4"},
{"apples":"5","oranges":"9","pear":"40"}]}' as json union all
select '{"fruit":[{"lettuce":"7","kale": "8"}]}'
)
select json, if(regexp_contains(json, '"apples":"5"'), (SELECT
ARRAY_AGG(json_extract_scalar(arr, '$.oranges') ignore nulls)
from
UNNEST(json_extract_ARRAY(json, '$.fruit')) as arr ), null) as oranges,
if(regexp_contains(json, '"apples":"5"'), (SELECT
ARRAY_AGG(json_extract_scalar(arr, '$.pear') ignore nulls)
from
UNNEST(json_extract_ARRAY(json, '$.fruit')) as arr ), null) as pear,
from `project.dataset.table`
I am expecting output like
| json | oranges | pear |
|---|---|---|
| {"fruit":[{"apples":"5","oranges":"10","pear":"20"},{"apples":"5","oranges":"4"},{"apples":"5","oranges":"9","pear":"40"}]} | 10 | 20 |
| 4 | null | |
| 9 | 40 | |
| {"fruit":[{"lettuce":"7","kale": "8"}]}. | null | null |



