How do I parse value from JSON array into columns in BigQuery

笑着哭i 提交于 2021-01-28 19:33:05

问题


I have a JSON array that is similar to this

{"key":"Email","slug":"customer-email","value":"abc@gmail.com"}
{"key":"Phone Number","slug":"mobile-phone-number","value":"123456789"}
{"key":"First Name","slug":"first-name","value":"abc"}
{"key":"Last Name","slug":"last-name","value":"xyz"}
{"key":"Date of birth","slug":"date-of-birth","value":"01/01/1990"}

I am hoping to turn the array into columns like this

email|          phoneNumber |  firstName |  lastName |  dob
abc@gmail.com   123456789      abc          xyz         01/01/1990

Any guides or inputs would be truly appreciated.


回答1:


Below is for BigQuery Standard SQL

#standardSQL
SELECT id, 
  MAX(IF(key = 'Email', value, NULL)) AS Email,
  MAX(IF(key = 'PhoneNumber', value, NULL)) AS PhoneNumber,
  MAX(IF(key = 'FirstName', value, NULL)) AS FirstName,
  MAX(IF(key = 'LastName', value, NULL)) AS LastName,
  MAX(IF(key = 'Dateofbirth', value, NULL)) AS Dateofbirth
FROM `project.dataset.table`,
UNNEST(ARRAY(
    SELECT AS STRUCT 
      REPLACE(JSON_EXTRACT_SCALAR(json, '$.key'), ' ', '') AS key,
      JSON_EXTRACT_SCALAR(json, '$.value') AS value
    FROM UNNEST(json_array) json
))
GROUP BY id   

You can test, play with above using sample data from your question as in below example

#standardSQL
WITH `project.dataset.table` AS (
  SELECT 1 id, [
    '{"key":"Email","slug":"customer-email","value":"abc@gmail.com"}',
    '{"key":"Phone Number","slug":"mobile-phone-number","value":"123456789"}',
    '{"key":"First Name","slug":"first-name","value":"abc"}',
    '{"key":"Last Name","slug":"last-name","value":"xyz"}',
    '{"key":"Date of birth","slug":"date-of-birth","value":"01/01/1990"}'
  ] json_array
)
SELECT id, 
  MAX(IF(key = 'Email', value, NULL)) AS Email,
  MAX(IF(key = 'PhoneNumber', value, NULL)) AS PhoneNumber,
  MAX(IF(key = 'FirstName', value, NULL)) AS FirstName,
  MAX(IF(key = 'LastName', value, NULL)) AS LastName,
  MAX(IF(key = 'Dateofbirth', value, NULL)) AS Dateofbirth
FROM `project.dataset.table`,
UNNEST(ARRAY(
    SELECT AS STRUCT 
      REPLACE(JSON_EXTRACT_SCALAR(json, '$.key'), ' ', '') AS key,
      JSON_EXTRACT_SCALAR(json, '$.value') AS value
    FROM UNNEST(json_array) json
))
GROUP BY id   

with output

Row id  Email           PhoneNumber     FirstName   LastName    Dateofbirth  
1   1   abc@gmail.com   123456789       abc         xyz         01/01/1990  


来源:https://stackoverflow.com/questions/63734411/how-do-i-parse-value-from-json-array-into-columns-in-bigquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!