hive中get_json_object函数不支持解析json中文key

这篇具有很好参考价值的文章主要介绍了hive中get_json_object函数不支持解析json中文key。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

问题

今天在 Hive 中 get_json_object 函数解析 json 串的时候,发现函数不支持解析 json 中文 key。
例如:

select get_json_object('{ "姓名":"张三" , "年龄":"18" }', '$.姓名');

我们希望的结果是得到姓名对应的值张三,而运行之后的结果为 NULL 值。

select get_json_object('{ "abc姓名":"张三" , "abc":"18" }', '$.abc姓名');

我们希望的结果是得到姓名对应的值张三,而运行之后的结果为 18

产生问题的原因

是什么原因导致的呢?我们查看 Hive 官网中 get_json_object 函数的介绍,可以发现 get_json_object 函数不能解析 json 里面中文的 key,如下图所示:
hive中get_json_object函数不支持解析json中文key,# Hive,hive,get_json_object,json,不支持中文key
json 路径只能包含字符 [0-9a-z_],即不能包含 大写或特殊字符 。此外,键不能以数字开头。

那为什么 json 路径只能包含字符 [0-9a-z_] 呢?

通过查看源码我们发现 get_json_object 对应的 UDF 类的源码如下:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.fasterxml.jackson.core.json.JsonReadFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Iterators;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;

/**
 * UDFJson.
 */
@Description(name = "get_json_object",
        value = "_FUNC_(json_txt, path) - Extract a json object from path ",
        extended = "Extract json object from a json string based on json path "
                + "specified, and return json string of the extracted json object. It "
                + "will return null if the input json string is invalid.\n"
                + "A limited version of JSONPath supported:\n"
                + "  $   : Root object\n"
                + "  .   : Child operator\n"
                + "  []  : Subscript operator for array\n"
                + "  *   : Wildcard for []\n"
                + "Syntax not supported that's worth noticing:\n"
                + "  ''  : Zero length string as key\n"
                + "  ..  : Recursive descent\n"
                + "  @   : Current object/element\n"
                + "  ()  : Script expression\n"
                + "  ?() : Filter (script) expression.\n"
                + "  [,] : Union operator\n"
                + "  [start:end:step] : array slice operator\n")

//定义了一个名为UDFJson的类,继承自UDF类。
public class UDFGetJsonObjectCN extends UDF {
    //定义一个静态正则表达式模式,用于匹配JSON路径中的键。
    //匹配英文key:匹配一个或多个大写字母、小写字母、数字、下划线、连字符、冒号或空格。
    private static final Pattern patternKey = Pattern.compile("^([a-zA-Z0-9_\\-\\:\\s]+).*");
    //定义一个静态正则表达式模式,用于匹配JSON路径中的索引。
    private static final Pattern patternIndex = Pattern.compile("\\[([0-9]+|\\*)\\]");

    //创建一个ObjectMapper对象,用于解析JSON字符串。
    private static final ObjectMapper objectMapper = new ObjectMapper();
    //创建一个JavaType对象,用于表示Map类型。
    private static final JavaType MAP_TYPE = objectMapper.getTypeFactory().constructType(Map.class);
    //创建一个JavaType对象,用于表示List类型。
    private static final JavaType LIST_TYPE = objectMapper.getTypeFactory().constructType(List.class);


    //静态代码块,用于配置ObjectMapper的一些特性。
    static {
        // Allows for unescaped ASCII control characters in JSON values
        objectMapper.enable(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature());
        // Enabled to accept quoting of all character backslash qooting mechanism
        objectMapper.enable(JsonReadFeature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER.mappedFeature());
    }

    // An LRU cache using a linked hash map
    //定义了一个静态内部类HashCache,用作LRU缓存。
    static class HashCache<K, V> extends LinkedHashMap<K, V> {

        private static final int CACHE_SIZE = 16;
        private static final int INIT_SIZE = 32;
        private static final float LOAD_FACTOR = 0.6f;

        HashCache() {
            super(INIT_SIZE, LOAD_FACTOR);
        }

        private static final long serialVersionUID = 1;

        @Override
        protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
            return size() > CACHE_SIZE;
        }

    }

    //声明了一个名为extractObjectCache的HashMap对象,用于缓存已提取的JSON对象。
    Map<String, Object> extractObjectCache = new HashCache<String, Object>();
    //声明了一个名为pathExprCache的HashMap对象,用于缓存已解析的JSON路径表达式。
    Map<String, String[]> pathExprCache = new HashCache<String, String[]>();
    //声明了一个名为indexListCache的HashMap对象,用于缓存已解析的JSON路径中的索引列表。
    Map<String, ArrayList<String>> indexListCache =
            new HashCache<String, ArrayList<String>>();
    //声明了一个名为mKeyGroup1Cache的HashMap对象,用于缓存JSON路径中的键。
    Map<String, String> mKeyGroup1Cache = new HashCache<String, String>();
    //声明了一个名为mKeyMatchesCache的HashMap对象,用于缓存JSON路径中的键是否匹配的结果。
    Map<String, Boolean> mKeyMatchesCache = new HashCache<String, Boolean>();

    //构造函数,没有参数。
    public UDFGetJsonObjectCN() {
    }

    /**
     * Extract json object from a json string based on json path specified, and
     * return json string of the extracted json object. It will return null if the
     * input json string is invalid.
     *
     * A limited version of JSONPath supported: $ : Root object . : Child operator
     * [] : Subscript operator for array * : Wildcard for []
     *
     * Syntax not supported that's worth noticing: '' : Zero length string as key
     * .. : Recursive descent &amp;#064; : Current object/element () : Script
     * expression ?() : Filter (script) expression. [,] : Union operator
     * [start:end:step] : array slice operator
     *
     * @param jsonString
     *          the json string.
     * @param pathString
     *          the json path expression.
     * @return json string or null when an error happens.
     */
    //evaluate方法,用于提取指定路径的JSON对象并返回JSON字符串。
    public Text evaluate(String jsonString, String pathString) {
        if (jsonString == null || jsonString.isEmpty() || pathString == null
                || pathString.isEmpty() || pathString.charAt(0) != '$') {
            return null;
        }

        int pathExprStart = 1;
        boolean unknownType = pathString.equals("$");
        boolean isRootArray = false;

        if (pathString.length() > 1) {
            if (pathString.charAt(1) == '[') {
                pathExprStart = 0;
                isRootArray = true;
            } else if (pathString.charAt(1) == '.') {
                isRootArray = pathString.length() > 2 && pathString.charAt(2) == '[';
            } else {
                return null;
            }
        }

        // Cache pathExpr
        String[] pathExpr = pathExprCache.get(pathString);
        if (pathExpr == null) {
            pathExpr = pathString.split("\\.", -1);
            pathExprCache.put(pathString, pathExpr);
        }

        // Cache extractObject
        Object extractObject = extractObjectCache.get(jsonString);
        if (extractObject == null) {
            if (unknownType) {
                try {
                    extractObject = objectMapper.readValue(jsonString, LIST_TYPE);
                } catch (Exception e) {
                    // Ignore exception
                }
                if (extractObject == null) {
                    try {
                        extractObject = objectMapper.readValue(jsonString, MAP_TYPE);
                    } catch (Exception e) {
                        return null;
                    }
                }
            } else {
                JavaType javaType = isRootArray ? LIST_TYPE : MAP_TYPE;
                try {
                    extractObject = objectMapper.readValue(jsonString, javaType);
                } catch (Exception e) {
                    return null;
                }
            }
            extractObjectCache.put(jsonString, extractObject);
        }

        for (int i = pathExprStart; i < pathExpr.length; i++) {
            if (extractObject == null) {
                return null;
            }
            extractObject = extract(extractObject, pathExpr[i], i == pathExprStart && isRootArray);
        }

        Text result = new Text();
        if (extractObject instanceof Map || extractObject instanceof List) {
            try {
                result.set(objectMapper.writeValueAsString(extractObject));
            } catch (Exception e) {
                return null;
            }
        } else if (extractObject != null) {
            result.set(extractObject.toString());
        } else {
            return null;
        }
        return result;
    }

    //extract方法,递归地提取JSON对象。
    private Object extract(Object json, String path, boolean skipMapProc) {
        // skip MAP processing for the first path element if root is array
        if (!skipMapProc) {
            // Cache patternkey.matcher(path).matches()
            Matcher mKey = null;
            Boolean mKeyMatches = mKeyMatchesCache.get(path);
            if (mKeyMatches == null) {
                mKey = patternKey.matcher(path);
                mKeyMatches = mKey.matches() ? Boolean.TRUE : Boolean.FALSE;
                mKeyMatchesCache.put(path, mKeyMatches);
            }
            if (!mKeyMatches.booleanValue()) {
                return null;
            }

            // Cache mkey.group(1)
            String mKeyGroup1 = mKeyGroup1Cache.get(path);
            if (mKeyGroup1 == null) {
                if (mKey == null) {
                    mKey = patternKey.matcher(path);
                    mKeyMatches = mKey.matches() ? Boolean.TRUE : Boolean.FALSE;
                    mKeyMatchesCache.put(path, mKeyMatches);
                    if (!mKeyMatches.booleanValue()) {
                        return null;
                    }
                }
                mKeyGroup1 = mKey.group(1);
                mKeyGroup1Cache.put(path, mKeyGroup1);
            }
            json = extract_json_withkey(json, mKeyGroup1);
        }
        // Cache indexList
        ArrayList<String> indexList = indexListCache.get(path);
        if (indexList == null) {
            Matcher mIndex = patternIndex.matcher(path);
            indexList = new ArrayList<String>();
            while (mIndex.find()) {
                indexList.add(mIndex.group(1));
            }
            indexListCache.put(path, indexList);
        }

        if (indexList.size() > 0) {
            json = extract_json_withindex(json, indexList);
        }

        return json;
    }

    //创建一个名为jsonList的AddingList对象,用于存储提取出来的JSON对象。
    private transient AddingList jsonList = new AddingList();

    //定义了一个静态内部类AddingList,继承自ArrayList<Object>,用于添加JSON对象到jsonList中。
    private static class AddingList extends ArrayList<Object> {
        private static final long serialVersionUID = 1L;

        @Override
        public Iterator<Object> iterator() {
            return Iterators.forArray(toArray());
        }
        @Override
        public void removeRange(int fromIndex, int toIndex) {
            super.removeRange(fromIndex, toIndex);
        }
    };

    //extract_json_withindex方法,根据JSON路径中的索引提取JSON对象。
    @SuppressWarnings("unchecked")
    private Object extract_json_withindex(Object json, ArrayList<String> indexList) {
        jsonList.clear();
        jsonList.add(json);
        for (String index : indexList) {
            int targets = jsonList.size();
            if (index.equalsIgnoreCase("*")) {
                for (Object array : jsonList) {
                    if (array instanceof List) {
                        for (int j = 0; j < ((List<Object>)array).size(); j++) {
                            jsonList.add(((List<Object>)array).get(j));
                        }
                    }
                }
            } else {
                for (Object array : jsonList) {
                    int indexValue = Integer.parseInt(index);
                    if (!(array instanceof List)) {
                        continue;
                    }
                    List<Object> list = (List<Object>) array;
                    if (indexValue >= list.size()) {
                        continue;
                    }
                    jsonList.add(list.get(indexValue));
                }
            }
            if (jsonList.size() == targets) {
                return null;
            }
            jsonList.removeRange(0, targets);
        }
        if (jsonList.isEmpty()) {
            return null;
        }
        return (jsonList.size() > 1) ? new ArrayList<Object>(jsonList) : jsonList.get(0);
    }

    //extract_json_withkey方法,根据JSON路径中的键提取JSON对象。
    @SuppressWarnings("unchecked")
    private Object extract_json_withkey(Object json, String path) {
        if (json instanceof List) {
            List<Object> jsonArray = new ArrayList<Object>();
            for (int i = 0; i < ((List<Object>) json).size(); i++) {
                Object json_elem = ((List<Object>) json).get(i);
                Object json_obj = null;
                if (json_elem instanceof Map) {
                    json_obj = ((Map<String, Object>) json_elem).get(path);
                } else {
                    continue;
                }
                if (json_obj instanceof List) {
                    for (int j = 0; j < ((List<Object>) json_obj).size(); j++) {
                        jsonArray.add(((List<Object>) json_obj).get(j));
                    }
                } else if (json_obj != null) {
                    jsonArray.add(json_obj);
                }
            }
            return (jsonArray.size() == 0) ? null : jsonArray;
        } else if (json instanceof Map) {
            return ((Map<String, Object>) json).get(path);
        } else {
            return null;
        }
    }
}

代码做了一些注释,我们可以发现 private final Pattern patternKey = Pattern.compile("^([a-zA-Z0-9_\\-\\:\\s]+).*"); 这个就是匹配 key 的模式串,它的意思是匹配以数字、字母、_、-、:、空格 为开头的字符串。那么这个匹配模式串就决定了,get_json_object 函数无法匹配出 key 中带中文的键值对,即select get_json_object('{ "姓名":"张三" , "年龄":"18" }', '$.姓名'); 结果为 null;而 select get_json_object('{ "abc姓名":"张三" , "abc":"18" }', '$.abc姓名'); 中只能匹配以数字、字母、_、-、:、空格 为开头的字符串,所以将 abc姓名 中的 abc 当作 key 去取 value 值,所以得到的值为18

解决办法

知道问题的原因了,那么我们怎么解决这个问题呢,其实很简单,我们只需要修改代码中匹配 key 的正则表达式就可以了。
其实我们可以将 get_json_object 函数的源码拿出来重新写一个 UDF 函数就可以了。

Hive-2.1.1 版本

需要注意自己 Hive 的版本,我们以 Hive-2.1.1 版本为例,代码如下:

package com.yan.hive.udf;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.google.common.collect.Iterators;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParser.Feature;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;
import org.codehaus.jackson.type.JavaType;

/**
 * UDFJson.
 *
 */
@Description(name = "get_json_object_cn",
        value = "_FUNC_(json_txt, path) - Extract a json object from path ",
        extended = "Extract json object from a json string based on json path "
                + "specified, and return json string of the extracted json object. It "
                + "will return null if the input json string is invalid.\n"
                + "A limited version of JSONPath supported:\n"
                + "  $   : Root object\n"
                + "  .   : Child operator\n"
                + "  []  : Subscript operator for array\n"
                + "  *   : Wildcard for []\n"
                + "Syntax not supported that's worth noticing:\n"
                + "  ''  : Zero length string as key\n"
                + "  ..  : Recursive descent\n"
                + "  &amp;#064;   : Current object/element\n"
                + "  ()  : Script expression\n"
                + "  ?() : Filter (script) expression.\n"
                + "  [,] : Union operator\n"
                + "  [start:end:step] : array slice operator\n")
public class UDFGetJsonObjectCN extends UDF {
    //private final Pattern patternKey = Pattern.compile("^([a-zA-Z0-9_\\-\\:\\s]+).*");
    private final Pattern patternKey = Pattern.compile("^([^\\[\\]]+).*");
    private final Pattern patternIndex = Pattern.compile("\\[([0-9]+|\\*)\\]");

    private static final JsonFactory JSON_FACTORY = new JsonFactory();
    static {
        // Allows for unescaped ASCII control characters in JSON values
        JSON_FACTORY.enable(Feature.ALLOW_UNQUOTED_CONTROL_CHARS);
        // Enabled to accept quoting of all character backslash qooting mechanism
        JSON_FACTORY.enable(Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER);
    }
    private static final ObjectMapper MAPPER = new ObjectMapper(JSON_FACTORY);
    private static final JavaType MAP_TYPE = TypeFactory.fromClass(Map.class);
    private static final JavaType LIST_TYPE = TypeFactory.fromClass(List.class);

    // An LRU cache using a linked hash map
    static class HashCache<K, V> extends LinkedHashMap<K, V> {

        private static final int CACHE_SIZE = 16;
        private static final int INIT_SIZE = 32;
        private static final float LOAD_FACTOR = 0.6f;

        HashCache() {
            super(INIT_SIZE, LOAD_FACTOR);
        }

        private static final long serialVersionUID = 1;

        @Override
        protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
            return size() > CACHE_SIZE;
        }

    }

    static Map<String, Object> extractObjectCache = new HashCache<String, Object>();
    static Map<String, String[]> pathExprCache = new HashCache<String, String[]>();
    static Map<String, ArrayList<String>> indexListCache =
            new HashCache<String, ArrayList<String>>();
    static Map<String, String> mKeyGroup1Cache = new HashCache<String, String>();
    static Map<String, Boolean> mKeyMatchesCache = new HashCache<String, Boolean>();

    Text result = new Text();

    public UDFGetJsonObjectCN() {
    }

    /**
     * Extract json object from a json string based on json path specified, and
     * return json string of the extracted json object. It will return null if the
     * input json string is invalid.
     *
     * A limited version of JSONPath supported: $ : Root object . : Child operator
     * [] : Subscript operator for array * : Wildcard for []
     *
     * Syntax not supported that's worth noticing: '' : Zero length string as key
     * .. : Recursive descent &amp;#064; : Current object/element () : Script
     * expression ?() : Filter (script) expression. [,] : Union operator
     * [start:end:step] : array slice operator
     *
     * @param jsonString
     *          the json string.
     * @param pathString
     *          the json path expression.
     * @return json string or null when an error happens.
     */
    public Text evaluate(String jsonString, String pathString) {

        if (jsonString == null || jsonString.isEmpty() || pathString == null
                || pathString.isEmpty() || pathString.charAt(0) != '$') {
            return null;
        }

        int pathExprStart = 1;
        boolean isRootArray = false;

        if (pathString.length() > 1) {
            if (pathString.charAt(1) == '[') {
                pathExprStart = 0;
                isRootArray = true;
            } else if (pathString.charAt(1) == '.') {
                isRootArray = pathString.length() > 2 && pathString.charAt(2) == '[';
            } else {
                return null;
            }
        }

        // Cache pathExpr
        String[] pathExpr = pathExprCache.get(pathString);
        if (pathExpr == null) {
            pathExpr = pathString.split("\\.", -1);
            pathExprCache.put(pathString, pathExpr);
        }

        // Cache extractObject
        Object extractObject = extractObjectCache.get(jsonString);
        if (extractObject == null) {
            JavaType javaType = isRootArray ? LIST_TYPE : MAP_TYPE;
            try {
                extractObject = MAPPER.readValue(jsonString, javaType);
            } catch (Exception e) {
                return null;
            }
            extractObjectCache.put(jsonString, extractObject);
        }
        for (int i = pathExprStart; i < pathExpr.length; i++) {
            if (extractObject == null) {
                return null;
            }
            extractObject = extract(extractObject, pathExpr[i], i == pathExprStart && isRootArray);
        }
        if (extractObject instanceof Map || extractObject instanceof List) {
            try {
                result.set(MAPPER.writeValueAsString(extractObject));
            } catch (Exception e) {
                return null;
            }
        } else if (extractObject != null) {
            result.set(extractObject.toString());
        } else {
            return null;
        }
        return result;
    }

    private Object extract(Object json, String path, boolean skipMapProc) {
        // skip MAP processing for the first path element if root is array
        if (!skipMapProc) {
            // Cache patternkey.matcher(path).matches()
            Matcher mKey = null;
            Boolean mKeyMatches = mKeyMatchesCache.get(path);
            if (mKeyMatches == null) {
                mKey = patternKey.matcher(path);
                mKeyMatches = mKey.matches() ? Boolean.TRUE : Boolean.FALSE;
                mKeyMatchesCache.put(path, mKeyMatches);
            }
            if (!mKeyMatches.booleanValue()) {
                return null;
            }

            // Cache mkey.group(1)
            String mKeyGroup1 = mKeyGroup1Cache.get(path);
            if (mKeyGroup1 == null) {
                if (mKey == null) {
                    mKey = patternKey.matcher(path);
                    mKeyMatches = mKey.matches() ? Boolean.TRUE : Boolean.FALSE;
                    mKeyMatchesCache.put(path, mKeyMatches);
                    if (!mKeyMatches.booleanValue()) {
                        return null;
                    }
                }
                mKeyGroup1 = mKey.group(1);
                mKeyGroup1Cache.put(path, mKeyGroup1);
            }
            json = extract_json_withkey(json, mKeyGroup1);
        }
        // Cache indexList
        ArrayList<String> indexList = indexListCache.get(path);
        if (indexList == null) {
            Matcher mIndex = patternIndex.matcher(path);
            indexList = new ArrayList<String>();
            while (mIndex.find()) {
                indexList.add(mIndex.group(1));
            }
            indexListCache.put(path, indexList);
        }

        if (indexList.size() > 0) {
            json = extract_json_withindex(json, indexList);
        }

        return json;
    }

    private transient AddingList jsonList = new AddingList();

    private static class AddingList extends ArrayList<Object> {
        @Override
        public Iterator<Object> iterator() {
            return Iterators.forArray(toArray());
        }
        @Override
        public void removeRange(int fromIndex, int toIndex) {
            super.removeRange(fromIndex, toIndex);
        }
    };

    @SuppressWarnings("unchecked")
    private Object extract_json_withindex(Object json, ArrayList<String> indexList) {

        jsonList.clear();
        jsonList.add(json);
        for (String index : indexList) {
            int targets = jsonList.size();
            if (index.equalsIgnoreCase("*")) {
                for (Object array : jsonList) {
                    if (array instanceof List) {
                        for (int j = 0; j < ((List<Object>)array).size(); j++) {
                            jsonList.add(((List<Object>)array).get(j));
                        }
                    }
                }
            } else {
                for (Object array : jsonList) {
                    int indexValue = Integer.parseInt(index);
                    if (!(array instanceof List)) {
                        continue;
                    }
                    List<Object> list = (List<Object>) array;
                    if (indexValue >= list.size()) {
                        continue;
                    }
                    jsonList.add(list.get(indexValue));
                }
            }
            if (jsonList.size() == targets) {
                return null;
            }
            jsonList.removeRange(0, targets);
        }
        if (jsonList.isEmpty()) {
            return null;
        }
        return (jsonList.size() > 1) ? new ArrayList<Object>(jsonList) : jsonList.get(0);
    }

    @SuppressWarnings("unchecked")
    private Object extract_json_withkey(Object json, String path) {
        if (json instanceof List) {
            List<Object> jsonArray = new ArrayList<Object>();
            for (int i = 0; i < ((List<Object>) json).size(); i++) {
                Object json_elem = ((List<Object>) json).get(i);
                Object json_obj = null;
                if (json_elem instanceof Map) {
                    json_obj = ((Map<String, Object>) json_elem).get(path);
                } else {
                    continue;
                }
                if (json_obj instanceof List) {
                    for (int j = 0; j < ((List<Object>) json_obj).size(); j++) {
                        jsonArray.add(((List<Object>) json_obj).get(j));
                    }
                } else if (json_obj != null) {
                    jsonArray.add(json_obj);
                }
            }
            return (jsonArray.size() == 0) ? null : jsonArray;
        } else if (json instanceof Map) {
            return ((Map<String, Object>) json).get(path);
        } else {
            return null;
        }
    }
}

需要导入的依赖,要和自己集群的版本契合,Hadoop 的版本及 Hive 的版本。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.atguigu.hive</groupId>
    <artifactId>hivetest</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <hadoop.version>3.0.0</hadoop.version>
        <hive.version>2.1.1</hive.version>
        <jackson.version>1.9.2</jackson.version>
        <guava.version>14.0.1</guava.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-exec</artifactId>
            <version>${hive.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.hive/hive-jdbc -->
        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-jdbc</artifactId>
            <version>${hive.version}</version>
        </dependency>


        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-common</artifactId>
            <version>${hadoop.version}</version>
        </dependency>

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>${guava.version}</version>
        </dependency>

        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-jaxrs</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-xc</artifactId>
            <version>${jackson.version}</version>
        </dependency>


    </dependencies>
    
</project>

注意: 因为上述UDF中也用到了 com.google.guavaorg.codehaus.jackson,所以这两个依赖要和 hive 版本中所用的依赖版本一致。

Hive-4.0.0 版本

package com.yan.hive.udf;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.fasterxml.jackson.core.json.JsonReadFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Iterators;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;

/**
 * @author Yan
 * @create 2023-08-05 22:21
 * hive解析json中文key
 */
@Description(name = "get_json_object_cn",
        value = "_FUNC_(json_txt, path) - Extract a json object from path ",
        extended = "Extract json object from a json string based on json path "
                + "specified, and return json string of the extracted json object. It "
                + "will return null if the input json string is invalid.\n"
                + "A limited version of JSONPath supported:\n"
                + "  $   : Root object\n"
                + "  .   : Child operator\n"
                + "  []  : Subscript operator for array\n"
                + "  *   : Wildcard for []\n"
                + "Syntax not supported that's worth noticing:\n"
                + "  ''  : Zero length string as key\n"
                + "  ..  : Recursive descent\n"
                + "  &amp;#064;   : Current object/element\n"
                + "  ()  : Script expression\n"
                + "  ?() : Filter (script) expression.\n"
                + "  [,] : Union operator\n"
                + "  [start:end:step] : array slice operator\n")

//定义了一个名为UDFJson的类,继承自UDF类。
public class UDFGetJsonObjectCN extends UDF {
    //定义一个静态正则表达式模式,用于匹配JSON路径中的键。
    //匹配英文key:匹配一个或多个大写字母、小写字母、数字、下划线、连字符、冒号或空格。
    //private static final Pattern patternKey = Pattern.compile("^([a-zA-Z0-9_\\-\\:\\s]+).*");
    //可以匹配中文,\\p{L}来匹配任意Unicode字母字符,包括中文字符:英文、数字、下划线、连字符、冒号、空格和中文字符。
    //private static final Pattern patternKey = Pattern.compile("^([a-zA-Z0-9_\\-\\:\\s\\p{L}]+).*");
    //可以匹配中文,\\p{L}来匹配任意Unicode字母字符,包括中文字符,但不包含特殊字符,特殊字符需自己添加
    //private static final Pattern patternKey = Pattern.compile("^([a-zA-Z0-9_\\-\\:\\s?%*+\\p{L}]+).*");
    //可以匹配中文,包含特殊字符,但不包含英文下的点(.);还有就是匹配不到路径中的索引了
    //private static final Pattern patternKey = Pattern.compile("^(.+).*");
    //可以匹配中文,包含特殊字符,不包中括号"[]",但不包含英文下的点(.);这样就可以匹配路径中的索引了
    private static final Pattern patternKey = Pattern.compile("^([^\\[\\]]+).*");
    //定义一个静态正则表达式模式,用于匹配JSON路径中的索引。
    private static final Pattern patternIndex = Pattern.compile("\\[([0-9]+|\\*)\\]");

    //创建一个ObjectMapper对象,用于解析JSON字符串。
    private static final ObjectMapper objectMapper = new ObjectMapper();
    //创建一个JavaType对象,用于表示Map类型。
    private static final JavaType MAP_TYPE = objectMapper.getTypeFactory().constructType(Map.class);
    //创建一个JavaType对象,用于表示List类型。
    private static final JavaType LIST_TYPE = objectMapper.getTypeFactory().constructType(List.class);


    //静态代码块,用于配置ObjectMapper的一些特性。
    static {
        // Allows for unescaped ASCII control characters in JSON values
        objectMapper.enable(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature());
        // Enabled to accept quoting of all character backslash qooting mechanism
        objectMapper.enable(JsonReadFeature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER.mappedFeature());
    }

    // An LRU cache using a linked hash map
    //定义了一个静态内部类HashCache,用作LRU缓存。
    static class HashCache<K, V> extends LinkedHashMap<K, V> {

        private static final int CACHE_SIZE = 16;
        private static final int INIT_SIZE = 32;
        private static final float LOAD_FACTOR = 0.6f;

        HashCache() {
            super(INIT_SIZE, LOAD_FACTOR);
        }

        private static final long serialVersionUID = 1;

        @Override
        protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
            return size() > CACHE_SIZE;
        }

    }

    //声明了一个名为extractObjectCache的HashMap对象,用于缓存已提取的JSON对象。
    Map<String, Object> extractObjectCache = new HashCache<String, Object>();
    //声明了一个名为pathExprCache的HashMap对象,用于缓存已解析的JSON路径表达式。
    Map<String, String[]> pathExprCache = new HashCache<String, String[]>();
    //声明了一个名为indexListCache的HashMap对象,用于缓存已解析的JSON路径中的索引列表。
    Map<String, ArrayList<String>> indexListCache =
            new HashCache<String, ArrayList<String>>();
    //声明了一个名为mKeyGroup1Cache的HashMap对象,用于缓存JSON路径中的键。
    Map<String, String> mKeyGroup1Cache = new HashCache<String, String>();
    //声明了一个名为mKeyMatchesCache的HashMap对象,用于缓存JSON路径中的键是否匹配的结果。
    Map<String, Boolean> mKeyMatchesCache = new HashCache<String, Boolean>();

    //构造函数,没有参数。
    public UDFGetJsonObjectCN() {
    }

    /**
     * Extract json object from a json string based on json path specified, and
     * return json string of the extracted json object. It will return null if the
     * input json string is invalid.
     *
     * A limited version of JSONPath supported: $ : Root object . : Child operator
     * [] : Subscript operator for array * : Wildcard for []
     *
     * Syntax not supported that's worth noticing: '' : Zero length string as key
     * .. : Recursive descent &amp;#064; : Current object/element () : Script
     * expression ?() : Filter (script) expression. [,] : Union operator
     * [start:end:step] : array slice operator
     *
     * @param jsonString
     *          the json string.
     * @param pathString
     *          the json path expression.
     * @return json string or null when an error happens.
     */
    //evaluate方法,用于提取指定路径的JSON对象并返回JSON字符串。
    public Text evaluate(String jsonString, String pathString) {
        if (jsonString == null || jsonString.isEmpty() || pathString == null
                || pathString.isEmpty() || pathString.charAt(0) != '$') {
            return null;
        }

        int pathExprStart = 1;
        boolean unknownType = pathString.equals("$");
        boolean isRootArray = false;

        if (pathString.length() > 1) {
            if (pathString.charAt(1) == '[') {
                pathExprStart = 0;
                isRootArray = true;
            } else if (pathString.charAt(1) == '.') {
                isRootArray = pathString.length() > 2 && pathString.charAt(2) == '[';
            } else {
                return null;
            }
        }

        // Cache pathExpr
        String[] pathExpr = pathExprCache.get(pathString);
        if (pathExpr == null) {
            pathExpr = pathString.split("\\.", -1);
            pathExprCache.put(pathString, pathExpr);
        }

        // Cache extractObject
        Object extractObject = extractObjectCache.get(jsonString);
        if (extractObject == null) {
            if (unknownType) {
                try {
                    extractObject = objectMapper.readValue(jsonString, LIST_TYPE);
                } catch (Exception e) {
                    // Ignore exception
                }
                if (extractObject == null) {
                    try {
                        extractObject = objectMapper.readValue(jsonString, MAP_TYPE);
                    } catch (Exception e) {
                        return null;
                    }
                }
            } else {
                JavaType javaType = isRootArray ? LIST_TYPE : MAP_TYPE;
                try {
                    extractObject = objectMapper.readValue(jsonString, javaType);
                } catch (Exception e) {
                    return null;
                }
            }
            extractObjectCache.put(jsonString, extractObject);
        }

        for (int i = pathExprStart; i < pathExpr.length; i++) {
            if (extractObject == null) {
                return null;
            }
            extractObject = extract(extractObject, pathExpr[i], i == pathExprStart && isRootArray);
        }

        Text result = new Text();
        if (extractObject instanceof Map || extractObject instanceof List) {
            try {
                result.set(objectMapper.writeValueAsString(extractObject));
            } catch (Exception e) {
                return null;
            }
        } else if (extractObject != null) {
            result.set(extractObject.toString());
        } else {
            return null;
        }
        return result;
    }

    //extract方法,递归地提取JSON对象。
    private Object extract(Object json, String path, boolean skipMapProc) {
        // skip MAP processing for the first path element if root is array
        if (!skipMapProc) {
            // Cache patternkey.matcher(path).matches()
            Matcher mKey = null;
            Boolean mKeyMatches = mKeyMatchesCache.get(path);
            if (mKeyMatches == null) {
                mKey = patternKey.matcher(path);
                mKeyMatches = mKey.matches() ? Boolean.TRUE : Boolean.FALSE;
                mKeyMatchesCache.put(path, mKeyMatches);
            }
            if (!mKeyMatches.booleanValue()) {
                return null;
            }

            // Cache mkey.group(1)
            String mKeyGroup1 = mKeyGroup1Cache.get(path);
            if (mKeyGroup1 == null) {
                if (mKey == null) {
                    mKey = patternKey.matcher(path);
                    mKeyMatches = mKey.matches() ? Boolean.TRUE : Boolean.FALSE;
                    mKeyMatchesCache.put(path, mKeyMatches);
                    if (!mKeyMatches.booleanValue()) {
                        return null;
                    }
                }
                mKeyGroup1 = mKey.group(1);
                mKeyGroup1Cache.put(path, mKeyGroup1);
            }
            json = extract_json_withkey(json, mKeyGroup1);
        }
        // Cache indexList
        ArrayList<String> indexList = indexListCache.get(path);
        if (indexList == null) {
            Matcher mIndex = patternIndex.matcher(path);
            indexList = new ArrayList<String>();
            while (mIndex.find()) {
                indexList.add(mIndex.group(1));
            }
            indexListCache.put(path, indexList);
        }

        if (indexList.size() > 0) {
            json = extract_json_withindex(json, indexList);
        }

        return json;
    }

    //创建一个名为jsonList的AddingList对象,用于存储提取出来的JSON对象。
    private transient AddingList jsonList = new AddingList();

    //定义了一个静态内部类AddingList,继承自ArrayList<Object>,用于添加JSON对象到jsonList中。
    private static class AddingList extends ArrayList<Object> {
        private static final long serialVersionUID = 1L;

        @Override
        public Iterator<Object> iterator() {
            return Iterators.forArray(toArray());
        }
        @Override
        public void removeRange(int fromIndex, int toIndex) {
            super.removeRange(fromIndex, toIndex);
        }
    };

    //extract_json_withindex方法,根据JSON路径中的索引提取JSON对象。
    @SuppressWarnings("unchecked")
    private Object extract_json_withindex(Object json, ArrayList<String> indexList) {
        jsonList.clear();
        jsonList.add(json);
        for (String index : indexList) {
            int targets = jsonList.size();
            if (index.equalsIgnoreCase("*")) {
                for (Object array : jsonList) {
                    if (array instanceof List) {
                        for (int j = 0; j < ((List<Object>)array).size(); j++) {
                            jsonList.add(((List<Object>)array).get(j));
                        }
                    }
                }
            } else {
                for (Object array : jsonList) {
                    int indexValue = Integer.parseInt(index);
                    if (!(array instanceof List)) {
                        continue;
                    }
                    List<Object> list = (List<Object>) array;
                    if (indexValue >= list.size()) {
                        continue;
                    }
                    jsonList.add(list.get(indexValue));
                }
            }
            if (jsonList.size() == targets) {
                return null;
            }
            jsonList.removeRange(0, targets);
        }
        if (jsonList.isEmpty()) {
            return null;
        }
        return (jsonList.size() > 1) ? new ArrayList<Object>(jsonList) : jsonList.get(0);
    }

    //extract_json_withkey方法,根据JSON路径中的键提取JSON对象。
    @SuppressWarnings("unchecked")
    private Object extract_json_withkey(Object json, String path) {
        if (json instanceof List) {
            List<Object> jsonArray = new ArrayList<Object>();
            for (int i = 0; i < ((List<Object>) json).size(); i++) {
                Object json_elem = ((List<Object>) json).get(i);
                Object json_obj = null;
                if (json_elem instanceof Map) {
                    json_obj = ((Map<String, Object>) json_elem).get(path);
                } else {
                    continue;
                }
                if (json_obj instanceof List) {
                    for (int j = 0; j < ((List<Object>) json_obj).size(); j++) {
                        jsonArray.add(((List<Object>) json_obj).get(j));
                    }
                } else if (json_obj != null) {
                    jsonArray.add(json_obj);
                }
            }
            return (jsonArray.size() == 0) ? null : jsonArray;
        } else if (json instanceof Map) {
            return ((Map<String, Object>) json).get(path);
        } else {
            return null;
        }
    }
}

依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.atguigu.hive</groupId>
    <artifactId>hivetest</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <hadoop.version>3.3.1</hadoop.version>
        <hive.version>4.0.0</hive.version>
		<jackson.version>2.13.5</jackson.version>
		<guava.version>22.0</guava.version>
    </properties>

    <dependencies>
    
      	<dependency>
        	<groupId>com.fasterxml.jackson</groupId>
        	<artifactId>jackson-bom</artifactId>
        	<version>${jackson.version}</version>
        	<type>pom</type>
        	<scope>import</scope>
      	</dependency>
      
      	<dependency>
        	<groupId>com.google.guava</groupId>
        	<artifactId>guava</artifactId>
        	<version>${guava.version}</version>
      	</dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>


        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-jdbc</artifactId>
            <version>${hive.version}</version>
        </dependency>

    </dependencies>
    
</project>

Hive 版本不同,之间的依赖可能就有些许差距,如果不注意的话可能会报依赖错误。

参考文章:

get_json_object不能解析json里面中文的key

get_json_object源码

impala&hive自定义UDF解析json中文key文章来源地址https://www.toymoban.com/news/detail-656855.html

到了这里,关于hive中get_json_object函数不支持解析json中文key的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • flink1.17 实现 udf scalarFunctoin get_json_object 支持 非标准化json

    相比官方的json_value,该函数支持非标准化json,比如v是个object,但是非标准json会外套一层引号,内部有反引号. eg:  {\\\"kkkk2\\\":  \\\"{\\\"kkkk1\\\":\\\"vvvvvvv\\\"}\\\" } 支持value为 100L 这种java格式的bigint.    {\\\"k\\\":999L} 基于jsonPath 方便,可以获取多层级内部值

    2024年02月11日
    浏览(28)
  • Hive的窗口函数与行列转换函数及JSON解析函数

    查看系统内置函数 :show functions ; 显示内置函数的用法 : desc function lag; – lag为函数名 显示详细的内置函数用法 : desc function extended lag; 1.1 行转列 行转列是指多行数据转换为一个列的字段。 Hive行转列用到的函数 concat(str1,str2,...) 字段或字符串拼接 concat_ws(\\\'分割符\\\',str1,str2,

    2024年02月12日
    浏览(27)
  • 【hive 运维】hive注释/数据支持中文

    hive支持中文需要关注两个方面: 设置hive 元数据库中的一些表 设置hive-site.xml.   由于Hive元数据(表的属性、字段定义等)都是存储在Mysql中,所以在mysql连接中设置支持中文 characterEncoding=UTF-8 具体的在hive-site.xml中:   重启hive-server   建表   插入数据   注:含有中文列的表

    2024年02月14日
    浏览(56)
  • Flask - 返回 json 格式数据 - json 数据传输支持中文显示

    在 Flask 配置中加入下面一行代码就OK了。 Flask 返回 Json python flask 返回json数据 Flask 让jsonify返回的json串支持中文显示 flask或flask-restful的接口开发,返回的json数据能显示中文的方法

    2024年02月07日
    浏览(36)
  • hive解析json

    目录 一、背景 二、hive 解析 json 数据函数 1、get_json_object  2、json_tuple 3、使用嵌套子查询(explode+regexp_replace+split+json_tuple)解析json数组 4、使用 lateral view 解析json数组 5、解析非固定名称json 我们进行ETL(Extract-Transfer-Load)  过程中,经常会遇到从不同数据源获取的不同格式的数据,

    2024年02月09日
    浏览(25)
  • Hive解析JSON串

    Hive 处理 json 数据总体来说有两个方向的路走: 将 json 以字符串的方式整个入 Hive 表,然后通过使用 UDF 函数解析已经导入到 hive 中的数据,比如使用 LATERAL VIEW json_tuple 的方法,获取所需要的列名。 在导入之前将 json 拆成各个字段,导入 Hive 表的数据是已经解析过的。这将需

    2024年02月16日
    浏览(26)
  • Hive解析嵌套JSON数组

    同时发生的埋点数据往往会在一个json字符串里发送,形式是[json,json,json]的埋点数组,需要把这些数据拉平 把最外层的\\\"[“和”]\\\"去除 把\\\"},{“转换为”}|||{\\\" ,使用split函数根据\\\"|||\\\"把string转为array,LATERAL view explode()把array转为列 第二步的时候发现,内部的json数组也有\\\"},

    2024年02月12日
    浏览(32)
  • 7. Hive解析JSON字符串、JSON数组

    Hive解析JSON字符串 1. get_json_object 语法: get_json_object(json_string, path) json_string 是要解析的JSON字符串 path 是用于指定要提取的字段路径的字符串 局限性 get_json_object 函数的性能会受到 JSON数据的结构和大小 的影响。对于较复杂的嵌套结构,考虑使用Hive的其他函数或自定义函数来

    2024年02月11日
    浏览(39)
  • 深入了解MySQL中的JSON_ARRAYAGG和JSON_OBJECT函数

    在MySQL数据库中,JSON格式的数据处理已经变得越来越常见。JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,它可以用来存储和表示结构化的数据。MySQL提供了一些功能强大的JSON函数,其中两个关键的函数是JSON_ARRAYAGG和JSON_OBJECT。本文将深入探讨这两个函数的用途、

    2024年02月09日
    浏览(30)
  • Hive解析Json数组超全讲解

    在Hive中会有很多数据是用Json格式来存储的,如开发人员对APP上的页面进行埋点时,会将多个字段存放在一个json数组中,因此数据平台调用数据时,要对埋点数据进行解析。接下来就聊聊Hive中是如何解析json数据的。 #1. get_json_object 语法: get_json_object(json_string, \\\'$.key\\\') 说明:

    2024年02月06日
    浏览(31)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包