Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to parse json using json_populate_recordset in postgres

Tags:

I have a json stored as text in one of my database row. the json data is as following

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

to parse this i want to use postgresql method

json_populate_recordset()

when I post a command like

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; 

it gives me following error first argument of json_populate_recordset must be a row type

note : in the from clause "anoop" is the table name.

can anyone suggest me how to use the json_populate_recordset method to extract data from this json string.

I got method's reference from http://www.postgresql.org/docs/9.3/static/functions-json.html

like image 644
kenthewala Avatar asked Sep 11 '14 10:09

kenthewala


People also ask

How do I query JSON data in PostgreSQL?

Querying the JSON document PostgreSQL has two native operators -> and ->> to query JSON documents. The first operator -> returns a JSON object, while the operator ->> returns text. These operators work on both JSON as well as JSONB columns. There are additional operators available for JSONB columns.

What is Json_populate_recordset?

json_populate_recordset() is a system function expanding the top-level JSON array of objects to a set of rows. json_populate_recordset() was added in PostgreSQL 9.3.

Is Jsonb faster than JSON?

Json processes input faster than jsonb as there is no conversion involved in this. Jsonb converts the JSON data into the binary form so it has slightly slower input due to the binary conversion overhead. There is no change in the Schema design while working with JSON.


1 Answers

The first argument passed to pgsql function json_populate_recordsetshould be a row type. If you want to use the json array to populate the existing table anoop you can simply pass the table anoop as the row type like this:

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"}]'); 

Here the null is the default value to insert into table columns not set in the json passed.

If you don't have an existing table, you need to create a row type to hold your json data (ie. column names and their types) and pass it as the first parameter, like this anoop_type:

create TYPE anoop_type AS (id int, name varchar(100)); select * from json_populate_recordset(null :: anoop_type,          '[...]') --same as above 
like image 176
jediKnight Avatar answered Sep 23 '22 15:09

jediKnight