如何在postgres中使用json_populate_recordset解析json

时间:2014-09-11 10:52:34

标签: 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

2 个答案:

答案 0 :(得分:21)

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

答案 1 :(得分: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
 )
相关问题