gpt4 book ai didi

python - 使用 Python 将 JSON 对象导入 Postgresql

转载 作者:搜寻专家 更新时间:2023-10-30 19:45:02 24 4
gpt4 key购买 nike

我正在尝试使用 Python 将 JSON 数据导入 Postgresql,但是,当我将“via”字段与 JSONB 数据类型一起放置时,出现“psycopg2.ProgrammingError: can't adapt type 'dict'”错误在我在 Postgresql 数据库中创建的表中。有什么办法可以解决我的问题吗?任何帮助都可以。

示例.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"
}
}
}
}
]

我的代码.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))

最佳答案

一种解决方案是在插入数据库之前转储字典:

for item in data:
my_data = [item[field] for field in fields]
for i, v in enumerate(my_data):
if isinstance(v, dict):
my_data[i] = json.dumps(v)
insert_query = "INSERT INTO crm VALUES (%s, %s, %s, %s)"
cursor.execute(insert_query, tuple(my_data))

关于python - 使用 Python 将 JSON 对象导入 Postgresql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51145801/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com