skip to Main Content

I have a JSON column in bigquery as such

SELECT PARSE_JSON('{"a": [1,2,3], "b":[4,5,6]}') AS key_values;

enter image description here

Is it possible to write a query such that I can get the following?

I can have any number of keys so I cannot specify the key name in my query.

enter image description here

Seems like this should be really simple but I cannot figure it out 🙁

2

Answers


  1. You can use UNNEST operator along with CROSS JOIN s to have flattened result such as

    SELECT 'a' AS key, value
      FROM t,
           UNNEST(JSON_QUERY_ARRAY(json.a)) AS value
    UNION ALL
    SELECT 'b', value
      FROM t,
           UNNEST(JSON_QUERY_ARRAY(json.b)) AS value
    

    Demo

    Login or Signup to reply.
  2. I cannot specify the key name in my query.

    you can consider below.

    CREATE TEMP FUNCTION json_keys(input STRING) RETURNS Array<String>
    LANGUAGE js AS """
      return Object.keys(JSON.parse(input));
    """;
    
    CREATE TEMP FUNCTION json_values(input STRING) RETURNS Array<String>
    LANGUAGE js AS """
      return Object.values(JSON.parse(input));
    """;
    
    WITH sample_data AS (
      SELECT '{"a": [1,2,3], "b":[4,5,6]}' AS key_values
    )
    SELECT k, v
      FROM sample_data,
    UNNEST (json_keys(key_values)) k WITH offset JOIN
    UNNEST (json_values(key_values)) v0 WITH offset USING(offset),
    UNNEST (SPLIT(v0, ',')) v;
    

    Query results

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search