How do I add a 'root element' to a json file

94 views Asked by At

I made a SQL query (build up with CTE's) that results in 6 products with their attributes. The query is just select * from output an this results in the following table, with more columns than shown below:

|row | gender | prod_1| url_1 | prod_2 |  url_2| ...
|  1 |  male  |   nike| www.xy|  adidas| www.ap| ...
|  2 | female |   puma| www.zq|   apple| www.ad| ...

When this table is converted to a JSON it looks like this:

[{
  "gender": "male",
  "product_1": "nike",
  "url_1": "www.xy ",
  "product_2": "puma",
  ...,
  "gender": "female",
  "product_1": "adidas",
  "url_1": "www.xy ",
  "product_2": "apple",
  ...,
}]

However, I want to group the results by gender and make the results look like this:

{
   "male": {
       "product_1": "nike",
       "url_1": "www.xy",
       "product_2": "adidas",
       ...,
   }
   "female": {
       "product_1": "puma",
       "url_1": "www.zq",
       "product_2": "apple",
       ...,
   }
}

There are two root elements where all the different product (+ attributes) fall under. Does anybody know if and how this result is possible (with a query?).

My output now looks like this: enter image description here

But I want the output to look like this: enter image description here

1

There are 1 answers

6
Jaytiger On

Since a key of JSON object should be a column name in Bigquery, so simple workaround would be using STRUCT like below:

WITH sample_table AS (
  SELECT 'male' gender, 'nike' product_1, 'www.xy' url_1, 'puma' product_2, 'www.xyz' url_2
   UNION ALL
  SELECT 'female' gender, 'adidas' product_1, 'www.xy' url_1, 'apple' product_2, 'www.xyz' url_2
)
SELECT CASE gender
         WHEN 'male' THEN TO_JSON_STRING(STRUCT((SELECT AS STRUCT t.* EXCEPT(gender)) AS male))
         WHEN 'female' THEN TO_JSON_STRING(STRUCT((SELECT AS STRUCT t.* EXCEPT(gender)) AS female))
       END AS json
  FROM sample_table t;

enter image description here

Update

SELECT CASE gender -- actually this CASE is not necessary cause it generates same output without it
         WHEN 'male' THEN (SELECT AS STRUCT t.* EXCEPT(gender))
         WHEN 'female' THEN (SELECT AS STRUCT t.* EXCEPT(gender))
       END AS items
  FROM sample_table t;

enter image description here