json - 如何在 postgres 中使用 json_populate_recordset 解析 json

标签 json postgresql postgresql-9.3

我有一个 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

最佳答案

传递给 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

关于json - 如何在 postgres 中使用 json_populate_recordset 解析 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25785575/

相关文章:

postgresql - 使用 GORM 排序 postgres 索引

postgresql - 如何将 Hstore 键和值分解为 postgres 中的单独列

postgresql - 如何使用本地 GUI 工具访问远程 Postgres 数据库

json - 如何在 Postgres 中的 JSON 字段上创建索引?

javascript - 如何在json2html中使用onclick

javascript - 如何将外部 php 文件字符串分配给 javascript 变量?

python - 安装 twitter api 模块时无法加载 json 库

javascript - 如何将 ResultSet 转换为 JSON 对象

sql - JOIN PostgreSQL 中的两个表和 GROUP BY

postgresql - 查找存在时间戳的记录