Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postgresql stored procedure input json parsing

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

like image 935
bharath kollareddy Avatar asked Mar 21 '26 14:03

bharath kollareddy


1 Answers

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 
like image 56
Val K Avatar answered Mar 24 '26 19:03

Val K



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!