1
connection = psycopg2.connect("dbname=db1 user=postgres password=postgres")
cursor = connection.cursor()
cursor.execute("set search_path to public")

with open('json_template') as file:
    data = file.read()

query_sql = """
insert into table1 select * from
json_populate_recordset(NULL::table1, %s);
"""

# change .execute(query_sql) to .execute(query_sql, (data,))
cursor.execute(query_sql, (data,))
connection.commit()

So I am trying to pass the contents of "json_template.json" to a Postgres table, but when I do I get the this error: psycopg2.errors.InvalidParameterValue: cannot call json_populate_recordset on an object

I've created the table through psql cmd. Also, here are the contents of my json_template file:

{"key": "A123", "value": "15.6", "ts":"2020-10-07 13:28:43.399620+02:00"} Attaching screenshot: json_template.json.

Did some research on the error, however nothing came out. Also tried to rewrite the code in other fashion several times - still the same error.

Thank you in advance!

Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
  • 1
    The error: `psycopg2.errors.InvalidParameterValue: cannot call json_populate_recordset on an object` has the information you need. You cannot pass in a JSON object. And if you read the docs [JSON functions](https://www.postgresql.org/docs/current/functions-json.html) you find that it needs an array of objects. – Adrian Klaver Feb 07 '22 at 20:24
  • What is the data type of the target column? – RMA Dev Feb 07 '22 at 21:13

2 Answers2

0

You got a JSON object, so you need to use json_populate_record instead of json_populate_recordset, which works for an array of objects.

import psycopg2

con = psycopg2.connect(...)
cursor = con.cursor()

with open('json_template') as file:
    data = file.read()

query_sql = """
insert into table1 select * from
json_populate_record(NULL::table1, %s);
"""

cursor.execute(query_sql, (data,))
con.commit()
cursor.execute('select * from table1')
print(cursor.fetchall())

Out:

[('A123', '15.6', '2020-10-07 13:28:43.399620+02:00')]
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
0

I just changed the JSON file from:

{"key": "A123", "value": "15.6", "ts":"2020-10-07 13:28:43.399620+02:00"}

To:

[
    {
        "key": "A128",
        "value": "15.6",
        "ts": "2020-10-07 13:28:43.399620+02:00"
    }
]

And it worked. Thank you all for the help!