Is there a function in BigQuery to create a typed STRUCT
from a JSON
object? Here is an example of what I'm trying to do:
with tbl as (
SELECT
STRUCT<name STRING, age INT64>("Bob", 20) AS person_as_struct,
JSON '{"name": "Bob", "age": 20}' AS person_as_json
)
select
-- STRUCT -> JSON
TO_JSON(person_as_struct).age
-- JSON -> STRUCT
-- ???
from tbl
Yes, there is a function in BigQuery that allows you to create a typed STRUCT from a JSON object. The function you can use for this is JSON_EXTRACT_SCALAR.
Here is an example of how you can use JSON_EXTRACT_SCALAR to create a typed STRUCT from a JSON object:
with tbl as (
SELECT
STRUCT<name STRING, age INT64>("Bob", 20) AS person_as_struct,
JSON '{"name": "Bob", "age": 20}' AS person_as_json
)
select
-- STRUCT -> JSON
TO_JSON(person_as_struct).age,
-- JSON -> STRUCT
STRUCT(
name = JSON_EXTRACT_SCALAR(person_as_json, '$.name'),
age = JSON_EXTRACT_SCALAR(person_as_json, '$.age')
) as person_as_struct
from tbl
The JSON_EXTRACT_SCALAR function extracts the value of a JSON field as a scalar value. In this case, we are using it to extract the name and age fields from the person_as_json JSON object and creating a typed STRUCT with these values.
Update
You are correct that using JSON_EXTRACT_SCALAR as shown in the previous example would require you to hardcode the field names and data types of the STRUCT. This means that if the JSON object changes, you would need to update the query accordingly.
If you want to create a typed STRUCT from a JSON object in a more dynamic way, where the field names and data types are determined at runtime, you can use dynamic SQL to generate the query.
Here is an example of how you could use dynamic SQL to create a typed STRUCT from a JSON object in a more dynamic way:
with tbl as (
SELECT
STRUCT<name STRING, age INT64>("Bob", 20) AS person_as_struct,
JSON '{"name": "Bob", "age": 20}' AS person_as_json
)
select
-- STRUCT -> JSON
TO_JSON(person_as_struct).age,
-- JSON -> STRUCT
(
select
(
select
'STRUCT(' ||
string_agg(f.name || ' = ' || f.name, ', ') ||
')'
from
UNNEST(JSON_EXTRACT_ARRAY(person_as_json, '$.*')) f
) as person_as_struct_query
from
tbl
) as person_as_struct
from tbl
In this example, we are using the JSON_EXTRACT_ARRAY function to extract all the fields of the person_as_json JSON object as an array, and then we are using the string_agg function to concatenate the field names and values into a string that can be used as the query to create the typed STRUCT.
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.