1,
普通string类型json 格式根据key 返回 value 处理:
json_tuple(字段名,'k1','k2','等等') as (v1,v2,等等)
优点:同时获取一个json 数据中多个key value 值很方便,且能直接重命名; 如果key 不存在直接返回null 值
缺点:返回值默认string,获取value 值时不能直接进行类型转换;同一个sql 中只能使用一次 json_tuple 对json 格式数据直接处理;
实例:
spark.sql("select content,json_tuple(content,'content','title') as(newName1,newName2) from XXXXXXX").show()
+---------------------------------------------------------------+----------------+--------+
|content |newName1 |newName2|
+---------------------------------------------------------------+----------------+--------+
|{"content":"\u8c22\u8c22"} |谢谢 |null |
|{"content":"\u6b63\u786e\u7b54\u68483"} |正确答案3 |null |
|{"content":"\u591a\u9009\u9898"} |多选题 |null |
get_json_object(待解析string,'$.k')
优点:一次只能完全解析出一个key 对应的value 值,但是同一个sql 中能多次使用 get_json_object 根据key 获取value 值;
支持多层嵌套解析
缺点:不能像json_tuple一样 一次解析多个key 对应value 值
spark.sql("select content,get_json_object(content,'$.content'),get_json_object(content,'$.title') from XXXX").show()
+---------------------------------------------------------------+-----------------------------------+---------------------------------+
|content |get_json_object(content, $.content)|get_json_object(content, $.title)|
+---------------------------------------------------------------+-----------------------------------+---------------------------------+
|{"content":"\u8c22\u8c22"} |谢谢 |null |
|{"content":"\u6b63\u786e\u7b54\u68483"} |正确答案3 |null |
|{"content":"\u591a\u9009\u9898"} |多选题 |null |
|{"content":"\u3010\u672a\u77e5\u6d88\u606f\u7c7b\u578b\u3011"} |【未知消息类型】 |null |
get 多层值:
含义:解析 buyerinfo string 中key 为 buyerExpandInfoVo 其value值中 key 是attributionStoreId 对应的value值
get_json_object(buyerinfo, '$.buyerExpandInfoVo.attributionStoreId')
get 数组值:
含义:解析 buyerinfo string 中key 为 buyerExpandInfoVo 其对应value值为数组的第一个元素值
get_json_object(buyerinfo, '$.buyerExpandInfoVo[0]')
2,复合 string 类型: arry数组中元素是单个或者多个json (又是一个复合json格式) 复合j结构数据解析思路处理:
1,去掉 string 类型数据首尾[ 和 ]:regexp_extract(itemlist, '^\\[(.+)\\]$', 1)
2, 将1 中array 数组中元素间的分隔符转为 特殊符合:regexp_replace(regexp_extract(itemlist, '^\\[(.+)\\]$', 1), '\\},\\{"baseDiscountInfo"','\\}#@\\{"baseDiscountInfo"')
3, 根据 2 中的特殊符号,使用split 将整个2 处理后的结果转为array类型:split(regexp_replace(regexp_extract(itemlist, '^\\[(.+)\\]$', 1), '\\},\\{"baseDiscountInfo"','\\}#@\\{"baseDiscountInfo"'),'#@')
4, 使用 LATERAL VIEW explode 将数据炸裂,在使用json_tuple或者get_json_Object 获取指定key值即可
select
json_tuple(items, 'id', 'goodsId') as(id, goodsId)
from XXXXX
LATERAL VIEW explode(split(regexp_replace(regexp_extract(itemlist, '^\\[(.+)\\]$', 1), '\\},\\{"baseDiscountInfo"','\\}#@\\{"baseDiscountInfo"'),'#@')) views AS items