简体   繁体   English

BigQuery:从 json 对象数组中提取选定键的值

[英]BigQuery: Extract values of selected keys from an array of json objects

I have a json in bigQuery我在 bigQuery 中有一个 json

{
  "actors": {
    "stooges": [
      {
        "id": 1,
        "name": "Larry"
      },
      {
        "id": 2,
        "name": "Curly"
      },
      {
        "id": 3,
        "name": "Moe"
      }
    ]
  }
}

How do I extract each of the .name s in bigQuery.如何提取 bigQuery 中的每个.name

["Larry", "Curly", "Moe"]

Here are some handy bigQuery compatible statements(based on above json).这里有一些方便的 bigQuery 兼容语句(基于上面的 json)。

-- Declaring a bigQuery variable 
DECLARE json_data JSON DEFAULT (SELECT PARSE_JSON('{ "actors": {"stooges": [{"id": 1,"name": "Larry"},{"id": 2,"name": "Curly"},{"id": 3,"name": "Moe"}]}}'));

-- Select statement. But this is no good for my use case since I don't want to specify element index ([0]) as the array size is dynamic
SELECT JSON_EXTRACT(json_data, '$.actors.stooges[0].name');

You may try and consider below approach using JSON_EXTRACT_ARRAY() then unnest it and then use JSON_EXTRACT_SCALAR() to extract the values.您可以尝试使用JSON_EXTRACT_ARRAY()考虑以下方法,然后将其取消嵌套,然后使用JSON_EXTRACT_SCALAR()提取值。

select ARRAY(
  SELECT JSON_EXTRACT_SCALAR(json_array, '$.name') from UNNEST(JSON_EXTRACT_ARRAY(json_data,"$.actors.stooges"))json_array
)extracted_names

Output: Output: 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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