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<String> evaluate(String jsonString) {
if (StringUtils.isBlank(jsonString)) {
return null;
}
try {
JSONArray jsonArray = new JSONArray(jsonString);
List<String> 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;
}
}
}