使用 JSONPath 查找所有具有位于单独 属性 中的键的值

Find all values with some key located in separate property using JSONPath

我的客户在 GCP BigQuery 服务中将数据存储为 table,列名称为 people,类型为 string,包含 JSON数据

部分数据如下:

{
  "id": "someid",
  "data": [
    {
      "key": "country",
      "valueString": "USA"
    },
    {
      "key": "name",
      "valueString": "Peter"
    }
  ]
}

另一个:

{
  "id": "someid",
  "data": [
    {
      "key": "age",
      "valueString": "23"
    },
    {
      "key": "country",
      "valueString": "France"
    },
    {
      "key": "name",
      "valueString": "Peter"
    }
  ]
}

我想创建一个查询来查找 key="country":

的所有值
country|
-------|
USA    |
-------|
France |
-------|
USA    |
-------|
.......|

看来我需要使用JSON路径查询语言。我的初始版本是:

SELECT JSON_EXTRACT_SCALAR(people, "$.data[0].valueString") AS country
FROM table_name

但是并没有解决问题,因为这个字段可以存放0,1,...n个元素

您可以使用 json_query_array 和 unnest 来实现此目的

with j1 as (
  select  1 id, '{ "id": "someid",  "data": [    {      "key": "country",      "valueString": "USA"    },    {      "key": "name",      "valueString": "Peter"    }  ]}' as j
  union all 
  select 2 ,'{  "id": "someid",  "data": [    {      "key": "age",      "valueString": "23"    },    {      "key": "country",      "valueString": "Germany"    },    {      "key": "name",      "valueString": "Peter"    }  ]}'
),
j2 as (
    select 
    j1.id,
    JSON_EXTRACT_SCALAR(jj,'$.key') key, 
    JSON_EXTRACT_SCALAR(jj,'$.valueString') value 
    from j1,unnest(json_query_array(j, '$.data')) as jj
)
select id,value country from j2 where key='country'

我不知道 BigQuery,但如果它采用标准 JSONPath,请尝试

SELECT JSON_EXTRACT_SCALAR(people, "$.data[?(@.key == 'country')].valueString") AS country FROM table_name

这应该为每个数据项提供 valueString 键 == "country"。

https://github.com/json-path/JsonPath#path-examples

考虑下面的[超级]简单方法

select json_extract_scalar(json, '$.valueString') as country
from your_table, unnest(json_extract_array(people, '$.data')) json
where json_extract_scalar(json, '$.key') = 'country'    

如果应用于您问题中的示例数据 - 输出为