In bigquery, if we are interested in constructing json output, we can usually use struct for json object when the keys are known beforehand.
SELECT TO_JSON_STRING(STRUCT(key1))
FROM (SELECT "val1" as key1 UNION ALL
SELECT "val2" as key1)
Result
{"key1":"val1"}
{"key1":"val2"}
But in the case where the keys are dynamic, we really want a map type, similar to the avro map type
For example
SELECT *
FROM (SELECT "key1" as key, "val1" as val UNION ALL
SELECT "key2" as key, "val2" as val)
should return
{"key1": "val1", "key2": "val2"}
is there anyway to achieve this using BigQuery SQL?