0

I’m inserting json data into a jsonb column. when I use python to perform inserts by reading from a file , the data is inserted as string but when I insert directly by assigning json to a variable(commented below) then it is inserted as an object . What am I Doing wrong below ?

import json
import psycopg2
data = open('C:\\xx\\json\.     \temp1.json').read()
my_json = json.dumps(data)
connection = psycopg2.connect(user = 
"xxxxx",
password = 
"xxxxx",
host = "exx",
port = "54xx",
database = 
"dxxx")
cursor = connection.cursor()
insert_query = "insert into gna       (data) values (%s)"
cursor.execute(insert_query,     (my_json,))
connection.commit()
count = cursor.rowcount
print (count, 
"Record inserted successfully into xx table")
0

1 Answer 1

1

you escape your json :)

data = open('C:\\xx\\json\. \temp1.json').read() is a json string. Your can pass that to postgres and it should be interpreted as json as long as your file really contains a json string.

my_json = json.dumps(data) data is a string. If you dump a string you escape it explicitly saying "this is not a json object"

import json
from io import StringIO

f = StringIO('{"key": "value"}')

data = f.read() 
print(data)  # {"key": "value"}

data = json.dumps(data)
print(data)  # "{\"key\": \"value\"}"

data = json.dumps({"key": "value"})
print(data) # {"key": "value"}
Sign up to request clarification or add additional context in comments.

Comments

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.