DRV
DRV

Reputation: 756

How to insert json data into postgres database table

I m a beginner and trying to insert JSON values into the database using a tutorial

I have created the table using the following command

CREATE TABLE table_name( id character varying(50),
                         data json NOT NULL,
                         active boolean NOT NULL,
                         created_at timestamp with time zone NOT NULL,
                         updated_at timestamp with time zone NOT NULL,
                         CONSTRAINT table_name_pkey PRIMARY KEY (id)
                       );

The table is created with table_name.

Now I am trying to insert the values into the database:

INSERT INTO table_name
SELECT id,data,active,created_at,updated_at
FROM json_populate_record (NULL::table_name,
     '{
        "id": "1",
        "data":{
                "key":"value"
                },
         "active":true,
         "created_at": SELECT NOW(),
         "updated_at": SELECT NOW()
       }'
  );

It throws the following error

ERROR: Invalid input syntax for type JSON '{

Could anyone help me to resolve and insert the JSON values into the DB?

Upvotes: 15

Views: 73390

Answers (1)

user330315
user330315

Reputation:

You can't include arbitrary SQL commands inside a JSON string. From a JSON "perspective" SELECT NOW() is an invalid value because it lacks the double quotes. But even if you used "select now()" that would be executed as a SQL query and replaced with the current timestamp) .

But I don't understand why you are wrapping this into a jsonb_populate_record. The better solution (at least in my opinion) would be:

INSERT INTO table_name (id, data, active, created_at, updated_dat)
VALUES ('1', '{"key": "value"}', true, now(), now());

If you really want to complicate things, you need to use string concatenation:

SELECT id,data,active,created_at,updated_at
FROM json_populate_record (NULL::table_name,
     format('{
        "id": "1",
        "data":{
                "key":"value"
                },
         "active":true,
         "created_at": "%s", 
         "updated_at": "%s"
       }', now(), now())::json
  );

Upvotes: 27

Related Questions