I have a table with json variant
s that contain keys which may or may not be there depending on the API response.
example table:
create or replace temporary table test (variant_col variant);
insert into test(variant_col)
select parse_json('{"response": [{"key1":[1,2,3]}, {"key2":[7,8,9]}]}');
insert into test(variant_col)
select parse_json('{"response": [{"key2":[7,8,9]}]}');
I’d like to lateral flatten them based on their keys, and use key1
if it exists, else use key2
(which will always exist)
SELECT
iff(f2.value::int is null, 'key2', 'key1') as value_type,
ifnull(f2.value::int, f3.value::int) as desired_value
FROM
test,
LATERAL FLATTEN(input => response) as f1,
LATERAL FLATTEN(input => f1.value:key1) as f2,
LATERAL FLATTEN(input => f1.value:key2) as f3
;
2
Answers
We can solve this by giving an id to each row, and then we can
union all
the results of 2 queries – depending on the existence ofkey1
:If
flatten
is excluding the row from the result set, you can use OUTER => true, which will return a null row for zero-row expansionshttps://docs.snowflake.com/en/sql-reference/functions/flatten