I have a table that contains a string column containing a stringified list of JSON objects like so:
'[{"a": 5, "b": 6}, {"a": 7, "b": 8}]'
I would like to unnest this array, and then use json_extract() or json_extract_scalar() to get the values out of these objects.
It's unclear from BigQuery's JSON Function documentation that I'm able to do so using baked-in functionality.
Is a UDF required to accomplish this, or does this functionality exist in BigQuery?
The below UDF accomplishes what I'm looking for:
CREATE TEMP FUNCTION
JSON_EXTRACT_ARRAY(input STRING)
RETURNS ARRAY<STRING>
LANGUAGE js AS """
return JSON.parse(input).map(x => JSON.stringify(x));
""";
with
raw as (
select
1 as id,
'[{"a": 5, "b": 6}, {"a": 7, "b": 8}]' as body
)
select
id,
json_extract(entry, '$.a') as a,
json_extract(entry, '$.b') as b
from
raw,
unnest(json_extract_array(body)) as entry