3

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

1 Answer 1

7

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 
Sign up to request clarification or add additional context in comments.

3 Comments

can you please share the same information for the xml too if i have the same xml data how can we parse it and insert into the db?
can you share how you are calling the function
Just 'SELECT insert_from_json("jsontext goes here..."::json);' should work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.