【发布时间】:2023-04-08 23:15:01
【问题描述】:
我正在尝试使用 Python 将 JSON 数据导入 Postgresql,但是当我将“via”字段与 JSONB 数据类型一起放置时,出现“psycopg2.ProgrammingError: can't adapt type 'dict'”错误在我在 Postgresql 数据库中创建的表中。有什么办法可以解决我的问题吗?任何帮助都可以。
sample.json
[
{
"url": "https://www.abcd.com/",
"id": 123456789,
"external_id": null,
"via": {
"channel": "email",
"id": 4,
"source": {
"from": {
"address": "abc@abc.com",
"name": "abc def"
},
"rel": null,
"to": {
"address": "def@def.com",
"name": "def"
}
}
}
},
{
"url": "http://wxyz.com/",
"id": 987654321,
"external_id": null,
"via": {
"channel": "email",
"id": 4,
"source": {
"from": {
"address": "xyz@xyz.com",
"name": "uvw xyz"
},
"rel": null,
"to": {
"address": "zxc@zxc.com",
"name": "zxc"
}
}
}
}
]
my_code.py
import json
import psycopg2
connection = psycopg2.connect("host=localhost dbname=sample user=gerald password=1234")
cursor = connection.cursor()
data = []
with open('sample.json') as f:
for line in f:
data.append(json.loads(line))
fields = [
'url', #varchar
'id', #BigInt
'external_id', #BigInt Nullable
'via' #JSONB
]
for item in data:
my_data = [item[field] for field in fields]
insert_query = "INSERT INTO crm VALUES (%s, %s, %s, %s)"
cursor.execute(insert_query, tuple(my_data))
【问题讨论】:
-
仅供参考。 sample.json 的语法似乎是错误的。我会尽快进行编辑和重塑
标签: python json database list jsonb