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

news2025/1/16 0:58:57

问题

今天在 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,如下图所示:
在这里插入图片描述
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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/896841.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

直播系统源码协议探索篇(二):网络套接字协议WebSocket

上一篇我们分析了直播平台的会话初始化协议SIP&#xff0c;他关乎着直播平台的实时通信和多方互动技术的实现&#xff0c;今天我们来讲另一个协议&#xff0c;叫网络套接字协议WebSocket&#xff0c;WebSocket基于TCP在客户端与服务器建立双向通信的网络协议&#xff0c;并且可…

博客系统之自动化测试

背景&#xff1a;针对个人博客项目进行测试&#xff0c;个人博客主要由四个页面构成&#xff1a;登录页、列表页、详情页和编辑页&#xff0c;主要功能包括&#xff1a;用户登录功能、发布博客功能、查看文章详情功能、查看文章列表功能、删除文章功能、退出功能。对于个人博客…

mysql全文检索使用

数据库数据量10万左右&#xff0c;使用like %test%要耗费30秒左右&#xff0c;放弃该办法 使用mysql的全文检索 第一步:建立索引 首先修改一下设置: my.ini中ngram_token_size 1 可以通过 show variables like %token%;来查看 接下来建立索引:alter table 表名 add f…

C#与西门子PLC1500的ModbusTcp服务器通信1--项目背景

最近在一个120万元的项目中&#xff0c;涉及到modbustcp通信&#xff0c;我作为软件总工负责项目的通信程序开发&#xff0c;modbus是一个在工业自动化领域中的通信协议&#xff0c;可以是modbusrtu&#xff0c;modbusascii&#xff0c;modbustcp三个形式&#xff0c;具体来说是…

QT VS编译环境无法打开包括文件type_traits

这问题&#xff0c;别人给的处理方法都是&#xff1a; 添加环境变量执行vsvars32.bat/vcvarsall.bat/vsdevcmd.bat重新安装QT项目&#xff1a;执行qmake。。。。 个人不推荐配置环境编译&#xff0c;除非你非常熟&#xff0c;因为配置环境变量需要你知道有哪些路径需要添加&a…

SpringBoo t+ Vue 微人事 (十一)

职位修改操作 在对话框里面做编辑的操作 添加对话框 <el-dialogtitle"修改职位":visible.sync"dialogVisible"width"30%"><div><el-tag>职位名称</el-tag><el-input size"small" class"updatePosIn…

Vue2-全局事件总线、消息的订阅与发布、TodoList的编辑功能、$nextTick、动画与过渡

&#x1f954;&#xff1a;高度自律即自由 更多Vue知识请点击——Vue.js VUE2-Day9 全局事件总线1、安装全局事件总线2、使用事件总线&#xff08;1&#xff09;接收数据&#xff08;2&#xff09;提供数据&#xff08;3&#xff09;组件销毁前最好解绑 3、TodoList中的孙传父&…

Jenkins改造—nginx配置鉴权

先kill掉8082的端口进程 netstat -natp | grep 8082 kill 10256 1、下载nginx nginx安装 EPEL 仓库中有 Nginx 的安装包。如果你还没有安装过 EPEL&#xff0c;可以通过运行下面的命令来完成安装 sudo yum install epel-release 输入以下命令来安装 Nginx sudo yum inst…

Flutter 测试小结

Flutter 项目结构 pubspec.yaml 类似于 RN 的 package.json&#xff0c;该文件分别在最外层及 example 中有&#xff0c;更新该文件后&#xff0c;需要执行的 Pub get lib 目录下的 dart 文件为 Flutter 插件封装后的接口源码&#xff0c;方便在其他 dart 文件中调用 example 目…

vue 如何适配 web 夜间模式、暗黑模式、黑色主题 prefers-color-scheme: dark

vue 如何适配 web 夜间模式、暗黑模式、黑色主题 prefers-color-scheme: dark 一、暗黑模式越来越普遍 自苹果推出暗黑模式之后&#xff0c;Web 也有了对应的暗黑模式&#xff0c;默认情况下 Web 的暗黑模式是跟随系统的。 你只需要将暗黑模式的样式写到下面这样的媒体选择器中…

Ubuntu软件源、pip源大全,国内网站网址,阿里云、网易163、搜狐、华为、清华、北大、中科大、上交、山大、吉大、哈工大、兰大、北理、浙大

文章目录 一、企业镜像源1、阿里云2、网易1633、搜狐镜像4、华为 二&#xff1a;高校镜像源1、清华源2、北京大学3、中国科学技术大学源 &#xff08;USTC&#xff09;4、 上海交通大学5、山东大学6、 吉林大学开源镜像站7、 哈尔滨工业大学开源镜像站8、 西安交通大学软件镜像…

使用ChatGPT进行创意写作的缺点

Open AI警告ChatGPT的使用者要明白此工具的局限性&#xff0c;更不应完全依赖。作为一位创作者&#xff0c;这一点非常重要&#xff0c;应尽可能地避免让版权问题或不必要的文体问题出现在自己的作品中。[1] 毕竟使用ChatGPT进行创意写作目前还有以下种种局限或缺点[2]&#xf…

prompt工程(持续更新ing...)

诸神缄默不语-个人CSDN博文目录 我准备想办法把这些东西整合到我的ScholarEase项目里。 其实以现在GPT-4的能力来说&#xff0c;直接就当日常对话随便直接说、直接问&#xff0c;基本没有太大的问题。 有时使用更复杂、详细、明确的prompt可能会起到提升作用。 有一些简单的…

Open cv C++安装

注意;要退出conda的虚拟环境 依赖 1.更新系统 sudo apt-get update sudo apt-get upgrade 2.安装相关的依赖 sudo apt-get install build-essential cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev sudo apt-get install libjpeg-de…

【组合数学】CF1312 D

Problem - 1312D - Codeforces 题意&#xff1a; 思路&#xff1a; Code&#xff1a; #include <bits/stdc.h>#define int long longusing i64 long long;constexpr int N 2e5 10; constexpr int M 2e5 10; constexpr int mod 998244353; constexpr int Inf 1e1…

小记std::unique_copy使用方法

因博主工作经验有限&#xff0c;只能通过有限的使用场景来介绍该特性 https://en.cppreference.com/w/cpp/algorithm/unique_copy 使用场景 将一些元素拷贝到另一个地方&#xff0c;可以定义重复的规则&#xff0c;拷贝出来之后是不带有连续相同元素的元素集合 如果需要使用…

azure VM完全复制

创建虚拟机&#xff0c;并创建linux服务&#xff0c;可以参考 https://blog.csdn.net/m0_48468018/article/details/132267096 &#xff0c; https://blog.csdn.net/m0_48468018/article/details/132267315在虚拟机中点击磁盘快照&#xff0c;创建磁盘快照 通过磁盘快照创建磁盘…

【LeetCode75】第三十二题 链表最大孪生和

目录 题目: 示例: 分析: 代码: 题目: 示例: 分析: 题目让我们求出链表的最大孪生和&#xff0c;那么什么是孪生和呢&#xff0c;就是对称的节点就是孪生节点&#xff0c;他们的和就是孪生和。 比如第一个节点的孪生节点就是最后一个节点&#xff0c;第二个节点的孪生节点…

【Docker】已经创建好的Docker怎么设置开机自启

已经创建好的Docker怎么设置开机自启 1.使用命令Docker update来完成2.查看是否开启3.验证是否开启 1.使用命令Docker update来完成 操作步骤&#xff1a; docker update --restartalways 容器ID2.查看是否开启 docker inspect 容器Id看到这里RestartPolicy设置为如图&#…

Verilog 入门

Verilog 入门 本内容来自 牛客网Verilog入门特别版 1、一个没有输入和一个输出常数1的输出的电路&#xff0c;输出信号为one module top_module(one);output wire one;assign one 1b1; endmodule2、创建一个具有一个输入和一个输出的模块&#xff0c;其行为类似于电路上的连…