简体   繁体   中英

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

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: 在此处输入图像描述

But I want the output to look like this: 在此处输入图像描述

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;

在此处输入图像描述

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;

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM