I am new to PostgreSQL. Here is what I am trying to achieve. I will be getting a json as text as the input for the procedure and I need to parse them inside the procedure to get the data from them and save data into the tables.
Here is an example:
this is the table.
CREATE TABLE json_test2
(
id serial primary key,
name text,
age int
)
Now i am trying to create a procedure that will take a text as an input that contains json.
{
"data": [
{
"name": "kumar",
"age": 12
},
{
"name": "anand",
"age": 25
}
]
}
please create a proc that will meet my requirement
Why do you need the proc, it's just Postgres function:
INSERT INTO table_name (name, age)
SELECT (rec->>'name')::text , (rec->>'age')::integer FROM
json_array_elements('{ "data": [ { "name": "kumar", "age": 12 }, { "name": "anand", "age": 25 } ] }'::json->'data' ) rec
See http://www.postgresql.org/docs/9.3/static/functions-json.html
Proc:
CREATE FUNCTION insert_from_json(in_json_txt json) RETURNS void AS
$BODY$
INSERT INTO table_name (name, age)
SELECT (rec->>'name')::text , (rec->>'age')::integer FROM
json_array_elements(in_json_txt->'data') rec
$BODY$
LANGUAGE sql
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With