首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在字符串列bigquery中查询json

在字符串列bigquery中查询json
EN

Stack Overflow用户
提问于 2020-02-10 22:13:51
回答 1查看 25关注 0票数 1

我想知道是否有可能查询一个json字符串列,该列将在不指定索引的情况下对产品进行解嵌。

示例

代码语言:javascript
复制
with mytable as (
select 
'{"ecommerce":{"purchase":{"actionField":{"id":"T12345","affiliation":"Online Store","revenue":"35.43","tax":"4.90","shipping":"5.99","coupon":"SUMMER_SALE"},"products":[{"name":"Triblend Android T-Shirt","id":"12345","price":"15.25","brand":"Google","category":"Apparel","variant":"Gray","quantity":1,"coupon":""},{"name":"Donut Friday Scented T-Shirt","id":"67890","price":"33.75","brand":"Google","category":"Apparel","variant":"Black","quantity":1}]}}}' as eec
)  
select 
JSON_EXTRACT_SCALAR(eec, "$['ecommerce'].purchase.actionField.id") AS order_id,
JSON_EXTRACT_SCALAR(eec, "$['ecommerce'].purchase.products[0].name") AS product_1
from mytable
union all
select
JSON_EXTRACT_SCALAR(eec, "$['ecommerce'].purchase.actionField.id") AS order_id,
JSON_EXTRACT_SCALAR(eec, "$['ecommerce'].purchase.products[1].name") AS product_1
from mytable

预期输出

代码语言:javascript
复制
order_id    product_1
T12345  Triblend Android T-Shirt
T12345  Donut Friday Scented T-Shirt

enter image description here

但我希望获得此输出,而不必做一个产品索引的联合,但有一些东西,将重复和自动解嵌,因为有很多元素有产品

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-10 23:01:38

代码语言:javascript
复制
#standardSQL
CREATE TEMP FUNCTION json2array(input STRING)
RETURNS ARRAY<STRING>
LANGUAGE js AS """
  return JSON.parse(input).map(x=>JSON.stringify(x));
"""; 
WITH mytable AS (
  SELECT 
  '{"ecommerce":{"purchase":{"actionField":{"id":"T12345","affiliation":"Online Store","revenue":"35.43","tax":"4.90","shipping":"5.99","coupon":"SUMMER_SALE"},"products":[{"name":"Triblend Android T-Shirt","id":"12345","price":"15.25","brand":"Google","category":"Apparel","variant":"Gray","quantity":1,"coupon":""},{"name":"Donut Friday Scented T-Shirt","id":"67890","price":"33.75","brand":"Google","category":"Apparel","variant":"Black","quantity":1}]}}}' AS eec
)  
SELECT 
  JSON_EXTRACT_SCALAR(eec, "$['ecommerce'].purchase.actionField.id") AS order_id,
  JSON_EXTRACT_SCALAR(product, "$.name") AS product_1
FROM mytable,
UNNEST(json2array(JSON_EXTRACT(eec, "$['ecommerce'].purchase.products"))) product

带输出

代码语言:javascript
复制
Row order_id    product_1    
1   T12345      Triblend Android T-Shirt     
2   T12345      Donut Friday Scented T-Shirt    
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60152261

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档