【问题标题】:How to iterate trough JSON list in python and insert into PostgreSQL?如何遍历python中的JSON列表并插入PostgreSQL?
【发布时间】:2019-10-23 12:37:51
【问题描述】:

我有点卡住了,我能想到的解决方案都会以意大利面条式代码结束。

我有以下 JSON,我在 python 3 中创建了一个对象,我必须将值插入 PostgreSQL。

{
    "name": "test",
    "country": "DE",
    "time": "21-Oct-2019 (09:58:01.694763)",
    "toCurrency": ["EUR", "USD", "GBP"],
    "fromCurrency": ["DKK", "DKK", "DKK"],
    "buyMargin": ["1.2800", "1.2800", "2.0000"],
    "sellMargin": ["1.2800", "1.2800", "2.0000"],
    "unit": "M100" 
}

我遇到了异常:can only concatenate str (not "list") to str

  • 如何在 Python 中遍历这些列表并一次插入一个值?

同时每次都要插入'name'、'country'、'time'的其他值。

目前我可以插入这个 JSON:

{
"name": "test",
"country": "DE",
"time": "21-Oct-2019 (09:58:01.694763)",
"toCurrency": "EUR",
"fromCurrency": "DKK",
"buyMargin": "1.2800",
"sellMargin": "1.2800",
"unit": "M100" 
}

【问题讨论】:

  • 这些值是要插入json 列还是必须解析并插入8 个不同的列?
  • 它们将被插入到 8 个不同的列中

标签: python json python-3.x postgresql list


【解决方案1】:

使用 pandas 将您的数据转换为数据框。然后使用sqlalchemy,将此数据帧作为表存储在 PostGre 中。

import pandas as pd
from sqlalchemy import create_engine
d1 = {
    "name": "test",
    "country": "DE",
    "time": "21-Oct-2019 (09:58:01.694763)",
    "toCurrency": ["EUR", "USD", "GBP"],
    "fromCurrency": ["DKK", "DKK", "DKK"],
    "buyMargin": ["1.2800", "1.2800", "2.0000"],
    "sellMargin": ["1.2800", "1.2800", "2.0000"],
    "unit": "M100" 
}
df1 = pd.DataFrame(d1)
engine = create_engine(
        'postgresql://username:password@host:port/database')
df1.to_sql(tablename, engine, if_exists='append', index=False)

您的数据框将如下所示。并且将类似地存储为 PostGre 中的表

【讨论】:

  • 感谢您提供此解决方案!它非常干净和结构化。可以这样指定表的主键吗?
  • 创建表后,您可以从 postgres 本身执行此操作。
【解决方案2】:

如果我理解正确并且您的 toCurrencyfromCurrencybuyMarginsellMargin 具有相同数量的元素,它们应该具有相同数量的元素,那么以下应该对您有用:

j = {
    "name": "test",
    "country": "DE",
    "time": "21-Oct-2019 (09:58:01.694763)",
    "toCurrency": ["EUR", "USD", "GBP"],
    "fromCurrency": ["DKK", "DKK", "DKK"],
    "buyMargin": ["1.2800", "1.2800", "2.0000"],
    "sellMargin": ["1.2800", "1.2800", "2.0000"],
    "unit": "M100"
}

for idx, val in enumerate(j['toCurrency']):
    print(j['toCurrency'][idx], j['fromCurrency'][idx], j['buyMargin'][idx], j['sellMargin'][idx])

所以你的插入语句应该在打印的位置,你的列应该是相应的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-29
    • 2022-11-17
    • 1970-01-01
    相关资源
    最近更新 更多