更新时间:2023-10-25 GMT+08:00

get_json_object

get_json_object函数用于根据所给路径对json对象进行解析,当json对象非法时将返回NULL。

命令格式

get_json_object(string <json>, string <path>)

参数说明

表1 参数说明

参数

是否必选

参数类型

说明

json

STRING

标准的JSON格式对象,格式为{Key:Value, Key:Value,...}

path

STRING

表示在json中的path,以$开头。不同字符的含义如下:

  • $表示根节点。
  • .表示子节点。
  • []表示[number]表示数组下标,从0开始。
  • *表示Wildcard for [],返回整个数组。*不支持转义。

返回值说明

返回STRING类型的值。

  • 如果json为空或非法的json格式,返回NULL。
  • 如果json合法,path也存在,则返回对应字符串。

示例代码

  • 提取JSON对象src_json.json中的信息。命令示例如下。
    jsonString = {"store": {"fruit":[{"weight":8,"type":"apple"},{"weight":9,"type":"pear"}], "bicycle":{"price":19.95,"color":"red"} }, "email":"amy@only_for_json_udf_test.net", "owner":"Tony" } 

    提取owner字段信息,返回Tony。

    select get_json_object(jsonString, '$.owner'); 

    提取store.fruit字段第一个数组信息,返回{"weight":8,"type":"apple"}。

    select get_json_object(jsonString, '$.store.fruit[0]'); 

    提取不存在的字段信息,返回NULL。

    select get_json_object(jsonString, '$.non_exist_key');
  • 提取数组型JSON对象的信息。命令示例如下。

    返回22。

    select get_json_object('{"array":[["a",11],["b",22],["c",33]]}','$.array[1][1]'); 

    返回["h00","h11","h22"]。

    select get_json_object('{"a":"b","c":{"d":"e","f":"g","h":["h00","h11","h22"]},"i":"j"}','$.c.h[*]'); 

    返回["h00","h11","h22"]。

    select get_json_object('{"a":"b","c":{"d":"e","f":"g","h":["h00","h11","h22"]},"i":"j"}','$.c.h'); 

    返回h11。

    select get_json_object('{"a":"b","c":{"d":"e","f":"g","h":["h00","h11","h22"]},"i":"j"}','$.c.h[1]');
  • 提取带有.的JSON对象中的信息。命令示例如下。

    创建一张表。

    create table json_table (id string, json string); 

    向表中插入数据,Key带 "."

    insert into table json_table (id, json) values ("1", "{\"China.hangzhou\":{\"region\":{\"rid\":6}}}"); 

    向表中插入数据,Key不带 "."

    insert into table json_table (id, json) values ("2", "{\"China_hangzhou\":{\"region\":{\"rid\":7}}}"); 

    取rid的值,查询key为China.hangzhou,返回6。由于包含.,只能用['']来解析。

    select get_json_object(json, "$['China.hangzhou'].region['id']") from json_table where id =1; 

    取rid的值,查询key为China_hangzhou,返回7。查询方法有如下两种。

    select get_json_object(json, "$['China_hangzhou'].region['id']") from json_table where id =2; 
    select get_json_object(json, "$.China_hangzhou.region['id']") from json_table where id =2;
  • JSON输入为空或非法格式。命令示例如下。

    返回NULL。

    select get_json_object('','$.array[2]'); 

    返回NULL。

    select get_json_object('"array":["a",1],"b":["c",3]','$.array[1][1]');
  • JSON字符串涉及转义。命令示例如下。

    返回"3"。

    select get_json_object('{"a":"\\"3\\"","b":"6"}', '$.a');  

    返回'3'。

    select get_json_object('{"a":"\'3\'","b":"6"}', '$.a'); 
  • 一个JSON对象中可以出现相同的Key,可以成功解析。

    返回1。

    select get_json_object('{"b":"1","b":"2"}', '$.b');
  • 输出结果按照JSON字符串的原始排序方式输出。

    返回{"b":"3","a":"4"}。

    select get_json_object('{"b":"3","a":"4"}', '$');