combine column in json format in big query

Viewed 129

I have columns in bigquery like this:

enter image description here

expected output: enter image description here

I am trying to merge columns into json using bigquery. I am taking letter before underscore(common name ) as column then converting.

I am trying this query:

with selectdata as (

    SELECT a_firstname, a_middlename,a_lastname FROM `account_id.Dataset.Table_name`

)

select TO_JSON_STRING(t) AS json_data FROM selectdata AS t;

How can I join columns with condition or with case to achieve this output in bigquery

1 Answers

Consider below approach

create temp function  extract_keys(input string) returns array<string> language js as """
  return Object.keys(JSON.parse(input));
  """;
create temp function  extract_values(input string) returns array<string> language js as """
  return Object.values(JSON.parse(input));
  """;
select * except(row_id) from (
  select format('%t',t) row_id, 
    split(key, '_')[offset(0)] as col, 
    '{' || string_agg(format('"%s":"%s"', split(key, '_')[safe_offset(1)], value)) || '}' as value
  from your_table t, unnest(extract_keys(to_json_string(t))) key with offset
  join unnest(extract_values(to_json_string(t))) value with offset
  using(offset)
  group by row_id, col
)
pivot (any_value(value) for col in ('a','b','c'))            

if applied to sample data in your question - output is

enter image description here

Related