Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert JSONB into Postgresql with Python?

I am new to python and postgresql

I've been battling just hardcoding each json line with python and I don't think this the scalable method. If someone can point me to the literature or documentation that can handle json insertion from python without hardcoding.

I've looked into COPY.

like image 248
Jonathan Avatar asked Sep 22 '17 23:09

Jonathan


1 Answers

import json

data = [1, [2,3], {'a': [4,5]}]
my_json = json.dumps(data)
insert_query = "insert into t (j) values (%s) returning j"
cursor.execute(insert_query, (my_json,))
print (cursor.fetchone()[0])

Output:

[1, [2, 3], {'a': [4, 5]}]
like image 149
Clodoaldo Neto Avatar answered Sep 26 '22 00:09

Clodoaldo Neto