今天这篇文章主要分析一下 hive 清洗 json 格式的数据,常用的两个函数。
第一个是
get_json_object
hive中解析一般的json是很容易的,使用 get_json_object 就可以了。 get_json_object 函数第一个参数填写json对象变量,第二个参数使用$表示json变量标识,然后用 . 或 [] 读取对象或数组;
例子:
select get_json_object('{"name":"jack","server":"www.qq.com"}','$.server')
json_tuple
对与返回多个字段的场景,它比 json_tuple 更加高效。具体是如何使用呢,下面给个实例
select
a.timestamp,
get_json_object(a.appevents, '$.eventid'),
get_json_object(a.appenvets, '$.eventname')
from log a;
可以改成如下写法:
select
a.timestamp,
b.*
from log a
lateral view json_tuple(a.appevent, 'eventid', 'eventname') b as f1, f2;
explode
但如果字段是json数组,比如
[{"bssid":"6C:59:40:21:05:C4"},{"bssid":"AC:9C:E4:04:EE:52","ssid":"and-Business"}]
直接调用 get_json_object 返回空值。这样的话对于不会写UDF的同学来说,解析json数组就变得很棘手,好在 hive 中自带了 explode 函数,从而让解析 json数组 变得有可能了。这里先介绍一下 explode 的使用方法:
explode(array)
select explode(array('A','B','C')) as col;
select tf.* from (select 0 from dual) t lateral view explode(array('A','B','C')) tf as col;
运行结果:
col 1
C
B
C