需求
有一下 json 數組,要求獲取其 key
[{"title":"笑傲江湖","author":"金庸"},{"title":"流星蝴蝶劍","author":"古龍"}]
需求實現
1、首先將 json 數組轉換為 字符串 ;這里使用 字符串替換函數 translate
select translate('[{"title":"笑傲江湖","author":"金庸"},{"title":"流星蝴蝶劍","author":"古龍"}]', '[]{}""', '') json_str;
結果1
title:笑傲江湖,author:金庸,title:流星蝴蝶劍,author:古龍
2、使用 regexp_replace 將中間的 , 替換成 ;
select regexp_replace(translate('[{"title":"笑傲江湖","author":"金庸"},{"title":"流星蝴蝶劍","author":"古龍"}]', '[]{}""', ''), '\,', '\:') json_str;
結果2
title:笑傲江湖:author:金庸:title:流星蝴蝶劍:author:古龍
3、使用 lateral view posexplode 炸開結果
select * from (select regexp_replace(translate('[{"title":"笑傲江湖","author":"金庸"},{"title":"流星蝴蝶劍","author":"古龍"}]', '[]{}""', ''), '\,', '\:') json_str) t lateral view posexplode(split(json_str, ':')) t1 as rn, value;
結果3
title:笑傲江湖:author:金庸:title:流星蝴蝶劍:author:古龍 0 title title:笑傲江湖:author:金庸:title:流星蝴蝶劍:author:古龍 1 笑傲江湖 title:笑傲江湖:author:金庸:title:流星蝴蝶劍:author:古龍 2 author title:笑傲江湖:author:金庸:title:流星蝴蝶劍:author:古龍 3 金庸 title:笑傲江湖:author:金庸:title:流星蝴蝶劍:author:古龍 4 title title:笑傲江湖:author:金庸:title:流星蝴蝶劍:author:古龍 5 流星蝴蝶劍 title:笑傲江湖:author:金庸:title:流星蝴蝶劍:author:古龍 6 author title:笑傲江湖:author:金庸:title:流星蝴蝶劍:author:古龍 7 古龍
4、對以上結果進行過濾
select rn, value from (select * from (select regexp_replace( translate('[{"title":"笑傲江湖","author":"金庸"},{"title":"流星蝴蝶劍","author":"古龍"}]', '[]{}""', ''), '\,', '\:') json_str) t lateral view posexplode(split(json_str, ':')) t1 as rn, value) t where rn % 2 = 0;
最終結果
0 title 2 author 4 title 6 author
另一種實現方式,使用兩層translate 替換后側寫,參考實現
select value from (select translate(info, ',', ':') info from (select translate('[{"title":"笑傲江湖","author":"金庸"},{"title":"流星蝴蝶劍","author":"古龍"}]', '{}[]"', '') info) t) t lateral view posexplode(split(info, ':')) t as rn, value where rn % 2 = 0 group by value;