如何计算 Snowflake 数据库变体字段中顶级 json 键的数量?

How can I count the number of top level json keys in a Snowflake database variant field?

我在这里寻找数字 2...array_size 似乎适用于变体列表,但在 json 上表现不佳。有没有聪明的方法来做到这一点?我不 know/probably 不能相信结构只会深入到这个程度,我希望将它用作查询的另一个字段,我从 [= 中提取了一堆其他值16=];所以理想情况下,解决方案也允许这样做。

select dict, array_size(dict)
from (select parse_json('{
  "partition": [
    "partition_col"
  ],
  "sample_weight": [
    "sample_weight"
  ]
}') as dict)

使用展平:

with dict as (
  select parse_json('{
    "partition": [
      "partition_col"
    ],
    "sample_weight": [
      "sample_weight"
    ]
  }') val
)
select val, count(*) 
from   dict,
       lateral flatten(input => val)
group by val
;

在这种情况下,您可以创建一个小的 Javascript UDF:

create or replace function count_keys(MYVAR variant)
returns float
language javascript
as '
    return (Object.entries(MYVAR)).length
'
;

调用它:

select count_keys(parse_json(
'{
    "partition": [
      "partition_col"
    ],
    "sample_weight": [
      "sample_weight"
    ]
  }')
)
;