从Hive中的字符串获取特定值

时间:2019-05-22 22:55:52

标签: json hive hiveql

我有一个配置单元表,其中两列都是字符串

name            details
"john" , {"addr":"NY","phone":"1234"}
"john" , {"addr":"CA", "phone":"7145"}
"mary" , {"addr":"BOS","phone":"1234"}  

有没有一种方法可以将字符串列转换为JSON类型,以通过键访问值。 如果我运行查询的示例

SELECT name, details['addr'] , details['phone'] FROM table_a;

我应该得到 纽约,约翰,1234 约翰(CA)7145 玛丽,BOS,1234

2 个答案:

答案 0 :(得分:0)

您可以使用get_json_object,然后从字符串访问addrphone

hive>  with cte as (
        select string('"john"')col1,
               string('{"addr":"NY","phone":"1234"}')col2)
        select regexp_replace(col1,"\"","")col1,get_json_object(col2,'$.addr')col2 
        from cte;

Result:

col1    col2
john    NY

为了转义引号,我们还可以使用here中所述的带引号字符的csv serde。

答案 1 :(得分:0)

使用str_to_map的另一种方法:

select name, details_map['addr'] as addr , details_map['phone'] as phone
from 
(
select name, str_to_map(regexp_replace(details,'\\{|\\}| ?\\"','')) as details_map
from your_table
)s;