主要有3种方法:
前两种内置方法,第三种是UDF,利用python脚本解析
- 1、get_json_object
- 2、json_tuple
- 3、python transform
具体的:
- 1、
get_json_object()
接受两个参数,第一个参数是json对象变量;第二个参数用$
来表示json对象变量,用.和[]
来读取对象或数组;
eg1:
select get_json_object('{"shop":{"book":[{"price":43.3,"type":"art"},{"price":30,"type":"technology"}],"clothes":{"price":19.951,"type":"shirt"}},"name":"jane","age":"23"}', '$.shop.book[0].type')
执行结果:
art
如果json比较简单:
eg2:
select get_json_object('{"name":"jack","server":"www.qq.com"}','$.server')
执行结果:
www.qq.com
但是存在一个问题,一个get_json_object只能解析一个字段,如果要解析多个字段,则需要使用多个get_json_object来读取,比较麻烦
- 2、json_tuple
可以同时解析一个json中的多个字段
eg:
select json_tuple('{"name":"jack","server":"www.qq.com"}','server','name')
执行结果:
www.qq.com jack
但是存在的问题是,只能解析简单的json,不能使用.和[]
的符号解析复杂json格式
- 3、python脚本解析(hive表中)
add file file_name;
insert overwrite table to_table
select
transform(col1,col2,col3)// from_table
using 'python file_name'
as
(uid,mid)//to_table
from from_table
python脚本中使用
import json
map = json.loads(line.strip())
uid = map.get('uid')
网友评论