【问题标题】:how to parse json using json_populate_recordset in postgres如何在 postgres 中使用 json_populate_recordset 解析 json
【发布时间】:2014-11-05 07:00:40
【问题描述】:

我有一个 json 作为文本存储在我的数据库行之一中。 json数据如下

[{"id":67272,"name":"EE_Quick_Changes_J_UTP.xlsx"},{"id":67273,"name":"16167.txt"},{"id":67274,"name":"EE_12_09_2013_Bcum_Searchall.png"}]

要解析这个我想使用 postgresql 方法

json_populate_recordset()

当我发布类似

的命令时
select json_populate_recordset(null::json,'[{"id":67272,"name":"EE_Quick_Changes_J_UTP.xlsx"},{"id":67273,"name":"16167.txt"},{"id":67274,"name":"EE_12_09_2013_Bcum_Searchall.png"}]') from anoop;

它给了我以下错误 json_populate_recordset 的第一个参数必须是行类型

注意:在 from 子句中“anoop”是表名。

谁能建议我如何使用 json_populate_recordset 方法从这个 json 字符串中提取数据。

我的方法参考来自 http://www.postgresql.org/docs/9.3/static/functions-json.html

【问题讨论】:

    标签: json postgresql postgresql-9.3


    【解决方案1】:

    无需为此创建新类型。

    select * from json_populate_recordset(null::record,'[{"id_item":1,"id_menu":"34"},{"id_item":2,"id_menu":"35"}]')
     AS
     (
        id_item int
        , id_menu int
     )
    

    【讨论】:

    • 如果我从表中查询不使用创建类型的语法是什么
    • 错误:记录类型尚未注册
    • 当一个 5 年前的问题只比我第一次访问大几个星期时,我总是很开心......
    【解决方案2】:

    传递给 pgsql 函数json_populate_recordset的第一个参数应该是一个行类型。如果您想使用 json 数组填充现有表 anoop,您可以简单地将表 anoop 作为行类型传递,如下所示:

    insert into anoop
    select * from json_populate_recordset(null::anoop, 
            '[{"id":67272,"name":"EE_Quick_Changes_J_UTP.xlsx"},
              {"id":67273,"name":"16167.txt"},
              {"id":67274,"name":"EE_12_09_2013_Bcum_Searchall.png"}]');
    

    这里null 是插入到未在传递的json 中设置的表列中的默认值。

    如果你没有现有的表,你需要create a row type来保存你的json数据(即列 名称及其类型)并将其作为第一个参数传递,例如 anoop_type:

    create TYPE anoop_type AS (id int, name varchar(100));
    select * from json_populate_recordset(null :: anoop_type, 
            '[...]') --same as above
    

    【讨论】:

    • 这是我发现的第一个用简单英语解压 null::anoop 的答案。谢谢!也就是说,我不明白 null 的值,因为大多数记录都有很多数据类型。除了 null,我们还可以为需要字符串、uuid 和 ints 的记录提供哪些其他默认值?
    猜你喜欢
    • 1970-01-01
    • 2014-05-10
    • 1970-01-01
    • 1970-01-01
    • 2015-10-21
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多