I currently have a JSON array that looks like this in Big Query:
[{"name":"","username":null},{"name":"Jimmy Dean","username":"iamjc"},{"name":"Ben Simmons","username":"bens"}]
I want to create a column that just has a list of username values. For the example above, I would like the column to display
"iamjc", "bens"
I've tried using json_extract_scalar with unnest but it is throwing an error because of the null value.
CREATE TEMP FUNCTION json2array(json STRING)
RETURNS ARRAY<STRING>
LANGUAGE js AS """
return JSON.parse(json).map(x=>JSON.stringify(x));
""";
select
g.created_at as message_sent,
username as sender,
members as original_members,
ARRAY(SELECT JSON_EXTRACT_SCALAR(x, '$.username')
FROM UNNEST(json2array(JSON_EXTRACT(members, '$'))) x
) AS members
from `table_1` g
join `table_2` u
on u._id = json_value(g.user, "$.id") and is_staff is false
where g.type = 'message.new'
order by 1 desc
The error on output is this:
Array cannot have a null element; error in writing field members
Would anyone know how to get this desired output?
Just add
WHERE
clause as in below exampleOr, use below option (in which case you don't even need
json2array
UDFif applied to dummy data as in your question
output is