Hive将Json字符串数组转为Json对象数组

一. maven pom.xml

 
        
            org.apache.hive
            hive-exec
            2.1.1
        
    

二.  UDF代码

package com.cn.bigdata.hive.func;

import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.json.JSONArray;
import org.json.JSONException;

import java.util.List;

/**
 * @description Convert a string of a JSON-encoded array to a Hive array of strings
 */
@Description(name = "json_array", value = "_FUNC_(array_string) - Convert a string of a JSON-encoded array to a Hive array of strings.")
public class JsonArray extends UDF {

    public List evaluate(String jsonString) {
        if (StringUtils.isBlank(jsonString)) {
            return null;
        }
        try {
            JSONArray jsonArray = new JSONArray(jsonString);
            List result = Lists.newArrayList();
            for (int i = 0; i < jsonArray.length(); i++) {
                result.add(jsonArray.get(i).toString());
            }
            return result;
        } catch(JSONException | NumberFormatException e) {
            return null;
        }
    }

}

你可能感兴趣的:(大数据,hive,hive,json,java)