简体   繁体   English

使用Python将JSON数据列表导入Postgresql

[英]Importing List of JSON data into Postgresql using Python

I'm trying to import a list of JSON Data into the Postgresql using Python but, I'm getting this error 我正在尝试使用Python将JSON数据列表导入到Postgresql中,但是出现此错误

psycopg2.ProgrammingError: can't adapt type 'dict' psycopg2.ProgrammingError:无法适应类型“ dict”

when I put the "custom_fields" field with a JSONB[] data type in my created table in the Postgresql Database. 当我在Postgresql数据库中创建的表中将具有JSONB []数据类型的“ custom_fields”字段放入时。 Is there any way to fix my problem? 有什么办法可以解决我的问题? Any help would do. 任何帮助都可以。 Thank you so much 非常感谢

//sample.json //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"
            }
        }
    },
    "custom_fields": [
        {
            "id": 234567891,
            "value": "abc_def_ghi"
        },
        {
            "id": 345678912, 
            "value": null
        },
        {
            "id": 456789123, 
            "value": null
        }
    ]
},

{
    "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"
            }
        }
    },
    "custom_fields": [
        {
            "id": 876543219, 
            "value": "zxc_vbn_asd"
        }, 
        {
            "id": 765432198, 
            "value": null
        }, 
        {
            "id": 654321987, 
            "value": null
        }
    ]   
}

//my_code.py //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 row in f:
        data.append(json.loads(row))

fields = [
    'url',
    'id',
    'external_id',
    'via',
    'custom_fields'
]

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

connection.commit()
connection.close()

Frameworks like SQLAlchemy would be my goto thing for operations like this. 像SQLAlchemy这样的框架将是我进行此类操作的首选。

JSON payload in above example is nested. 上面示例中的JSON有效负载是嵌套的。 You'll have to ensure that respective target DB in your DB reflect the same schema. 您必须确保数据库中的各个目标数据库反映相同的架构。

An example FYR: FYR示例:

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy_declarative import  Base, Review

engine = create_engine('sqlite:///sqlalchemy_try.db') #you might want to tweak this dialect to db of you choice. 
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)

session = DBSession()
with open('sample.json') as f:
    data=f.read()
    jsondata=json.loads(data)
    r = Review(jsondata['url'], int(jsondata['id']), jsondata['external_id'], jsondata['via']['channel']))
    session.add(r)
session.commit()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM