提取所有 JSON 键
Extract all JSON keys
我有一个 JSON 列 j
像:
{'a': 2, 'b': {'b1': 3, 'b2': 5}}
{'c': 3, 'a': 5}
{'d': 1, 'c': 7}
如何从 Presto 获取所有不同的(顶级)键名? IE。我喜欢
select distinct foo(j)
到return
['a', 'b', 'c', 'd']
(请注意,在这种情况下,我不太关心嵌套键)
Presto documentation doesn't have any function that explicitly fits the bill. The only thing that looks close is mention of JSONPath 语法,但即使这样似乎也不准确。至少以下一项应该 return something 但对我来说在 Presto 中都失败了:
select json_extract(j, '$.*')
select json_extract(j, '$..*')
select json_extract(j, '$[*]')
select json_extract(j, '*')
select json_extract(j, '..*')
select json_extract(j, '$*.*')
此外,我怀疑这将 return 来自 j
(即 [2, 3, 5, 3, 5, 1, 7]
)的 值 ,而不是键。
你可以
- 使用
map_keys(cast(json_column as map<varchar,json>))
提取JSON个顶级键
- 稍后 "flatten" 使用
CROSS JOIN UNNEST
的密钥集合
- 然后您可以
SELECT DISTINCT
获得不同的顶级密钥。
将其组合在一起的示例:
presto> SELECT DISTINCT m.key
-> FROM (VALUES JSON '{"a": 2, "b": {"b1": 3, "b2": 5}}', JSON '{"c": 3, "a": 5}')
-> example_table(json_column)
-> CROSS JOIN UNNEST (map_keys(CAST(json_column AS map<varchar,json>))) AS m(key);
key
-----
a
b
c
(3 rows)
我有一个 JSON 列 j
像:
{'a': 2, 'b': {'b1': 3, 'b2': 5}}
{'c': 3, 'a': 5}
{'d': 1, 'c': 7}
如何从 Presto 获取所有不同的(顶级)键名? IE。我喜欢
select distinct foo(j)
到return
['a', 'b', 'c', 'd']
(请注意,在这种情况下,我不太关心嵌套键)
Presto documentation doesn't have any function that explicitly fits the bill. The only thing that looks close is mention of JSONPath 语法,但即使这样似乎也不准确。至少以下一项应该 return something 但对我来说在 Presto 中都失败了:
select json_extract(j, '$.*')
select json_extract(j, '$..*')
select json_extract(j, '$[*]')
select json_extract(j, '*')
select json_extract(j, '..*')
select json_extract(j, '$*.*')
此外,我怀疑这将 return 来自 j
(即 [2, 3, 5, 3, 5, 1, 7]
)的 值 ,而不是键。
你可以
- 使用
map_keys(cast(json_column as map<varchar,json>))
提取JSON个顶级键
- 稍后 "flatten" 使用
CROSS JOIN UNNEST
的密钥集合
- 然后您可以
SELECT DISTINCT
获得不同的顶级密钥。
将其组合在一起的示例:
presto> SELECT DISTINCT m.key
-> FROM (VALUES JSON '{"a": 2, "b": {"b1": 3, "b2": 5}}', JSON '{"c": 3, "a": 5}')
-> example_table(json_column)
-> CROSS JOIN UNNEST (map_keys(CAST(json_column AS map<varchar,json>))) AS m(key);
key
-----
a
b
c
(3 rows)