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

标签 python json database list jsonb

我正在尝试使用 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/

相关文章:

php - 合并两个单独工作的 MySQL 查询

mysql - 如何选择SQL数据库表中的第n行?

python - 使用 Pandas groupby 的 Mathematica GatherBy 函数

python - 属性错误: 'Response' object has no attribute 'json'

sql - 避免 BigQuery 中 JSON_EXTRACT 函数中的指数表示法

ruby-on-rails - 如何在 ActionController::TestCase 请求中设置内容类型

php - 获取数据库行数据并设置变量

python - 如何从静态页面获取值并将其发布到模型中

python - 时间复杂度 : Cheapst Flights within K stops

包含 doctest.testmod() 的外部模块中的 python run 函数