经常有jason字符串需要解析后,取对应位置的数据,jason字符串可能是这样的:
{"Id":1,"type":1}
{"Id":2,"type":2}
{"Id":3,"type":3}
(这个只有两个字段,但是道理是一样的嘛)
这时只需要使用窗口函数get_json_object,具体代码如下:
select
get_json_object(info,'$.type') as type,
get_json_object(info,'$.id') as id
from t0
其中info是jason字符串的列名,结果如下:
id type
1 1
2 2
3 3
如果jason字符串变成了下面这种:
[{"Id":1,"type":1},{"Id":2,"type":2},{"Id":3,"type":3}]
那函数可不好使了哟,查询出来就是空了,所以需要先拆分再取字符串,代码如下:
select
tmp
from t0
lateral view explode(split(regexp_replace(regexp_replace(regexp_replace(info,'\\\]',''),
'\\\[',''),'\\\},\\\{','\\\}\001\\\{'),'\001')) tmp_list as tmp
得到的结果为:
tmp
{"Id":1,"type":1}
{"Id":2,"type":2}
{"Id":3,"type":3}
然后再使用窗口函数get_json_object即可;
我们在分割字符串时还用到了行转列的窗口函数lateral view explode,和split函数