I am new to presto and I have a table with a json column:
json-column
{"key-array":"[\"AAA\",\"BBB\",\"CCC\"]", "value-array":"[\"123\",\"456\",\"789\"]","str_1":"abc"}
I am trying to run the following query on the json-column.
select key,
value
from (
select cast(json_parse(json_payload) as map(varchar, json)) parsed
from my_table
) a,
unnest(
cast(json_parse(cast(parsed['key-arr'] as varchar)) as array(varchar)),
cast(json_parse(cast(parsed['val-arr'] as varchar)) as array(varchar))
) as t(key, value)
Now it is possible that the map entries might be null. So the query above fails whenever there are NULL entries.
An example of the data where the query fails is:
{"key-array":"", "value-array":"","str_1":"abc"}
This is the error I see:
presto error: Cannot cast to array(varchar). Expected a json array, but got null
Upon searching for possible solutions, I came across two functions filter and coalesce.
So I tried the following:
select key,
value
from (
select cast(json_parse(json_payload) as map(varchar, json)) parsed
from my_table
) a,
unnest(
cast(coalesce(json_parse(cast(parsed['key-arr'] as varchar)), json_parse(cast('["hello"]' as varchar))) as array(varchar)),
cast(coalesce(json_parse(cast(parsed['value-arr'] as varchar)), json_parse(cast('["hello1"]' as varchar))) as array(varchar))
) as t(key, value)
But I now get the following error:
presto error: Cannot convert value to JSON: ''
I am not sure what I am doing wrong here. Can someone kindly help me out here?