如何在postgres中使用json_populate_recordset解析json

问题描述 投票:11回答:2

我有一个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
2个回答
22
投票

传递给pgsql函数qazxswpo的第一个参数应该是行类型。如果你想使用json数组填充现有的表json_populate_recordset,你可以简单地将表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"}]'); 是插入到未在json传递中设置的表列的默认值。

如果你没有现有的表,你需要null来保存你的json数据(即列名和它们的类型)并将它作为第一个参数传递,就像这个create a row type

anoop_type

1
投票

无需为此创建新类型。

create TYPE anoop_type AS (id int, name varchar(100));
select * from json_populate_recordset(null :: anoop_type, 
        '[...]') --same as above
© www.soinside.com 2019 - 2024. All rights reserved.