GET_JSON_OBJECT用于解析JSON对象。本文为您介绍在交互式分析Hologres中GET_JSON_OBJECT的用法。

使用限制

  • 一个数据库只能在一个Schema下创建一次extension。例如在某数据库的public Schema下创建了extension,则此数据库下其余的Schema不能再创建extension。
  • 可以将extension直接创建在pg_catalog系统Schema下,就会默认所有数据库的所有Schema都能使用该功能。
  • 需要Superuser创建extension。

命令语法

GET_JSON_OBJECT的命令语法如下,在调用之前需要先创建extension。
--创建extension
CREATE extension if not exists hive_compatible schema $(schema_name);
SELECT get_json_object ( json_string, path );
说明 如需卸载extension请执行如下命令。
DROP extension hive_compatible;

参数说明

GET_JSON_OBJECT的参数说明如下表所示:
参数描述
json_stringJSON对象变量,TEXT类型。格式为合法JSON格式字符串。
pathJSON内层对象访问变量。使用$表示JSON变量标识,通过 . []读取JSON内层对象或数组。

如果您输入的JSON字符串无效,则系统返回NULL

使用示例

create extension if not exists hive_compatible schema pg_catalog;

begin;
create table hive_json_example(    
    col_json text
);
commit;

insert into hive_json_example values('{"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":"amy"}');

select get_json_object(col_json, '$.owner') from hive_json_example;
--Result: amy

select get_json_object(col_json, '$.store.bicycle.price') from hive_json_example;
--Result: 19.95

select get_json_object(col_json, '$.store.fruit[0]') from hive_json_example;
--Result: {"weight":8, "type":"apple"}

select get_json_object(col_json, '$.no_key') from hive_json_example;
--Result: NULL

常见报错

  • 报错:ERROR:function get_json_object (text, unknown) does not exist
    • 可能原因一

      在SLPM模式下RAM用户没有创建extension所在Schema的查询权限(例如extension指定创建在名称为public的Schema下,RAM用户没有public的查询权限)。

    • 解决方法一
      • 授予RAM用户Schema的查询权限。
      • 使用如下命令重新创建extension在pg_catalog下,所有账号都可查询。
        drop extension hive_compatible;
        create extension hive_compatible schema pg_catalog;
    • 可能原因二

      GET_JSON_OBJECT的第一个参数不是TEXT类型。

    • 解决方法二

      将第一个参数转换为TEXT类型。

  • 报错:ERROR: get_json_object for fe, should not be evaluated
    • 可能原因一

      GET_JSON_OBJECT的第一个参数是常量。

    • 解决方法一

      第一个参数使用表的列。

    • 可能原因二

      GET_JSON_OBJECT的第一个参数含有为NULL的值。

    • 解决方法二

      将第一个参数为NULL的值删除。