【问题标题】:insert json data into postgresql table using python使用python将json数据插入postgresql表
【发布时间】:2021-01-07 05:00:49
【问题描述】:

我需要编写一个自动化的 python 代码来创建数据库表,其中列名作为 json 文件中的键,列数据应该是这些相应键的值。 我的 json 看起来像这样:

    {
"Table_1": [
    {
        "Name": "B"
    }, 
    {
        "BGE3": [
            "Itm2", 
            "Itm1", 
            "Glass"
        ]
    }, 
    {
        "Trans": []
    }, 
    {
        "Art": [
            "SYS"
        ]
    }]}

我的表名应该是:Table_1。

所以我的列名应该是这样的:名称 | BGE3 |反式 |艺术。

而数据应该是其受人尊重的价值观。 表和列的创建必须是动态的,因为我需要在多个 json 文件上运行此代码。 到目前为止,我已经设法使用 python 连接到 postgresql 数据库。 所以请帮我解决问题。谢谢。

Postgres 版本 13。

现有代码:

cur.execute("CREATE TABLE Table_1(Name varchar, BGE3 varchar, Trans varchar, Art varchar)") 

for d in data: cur.execute("INSERT into B_Json_3(Name, BGE3, Trans , Art) VALUES (%s, %s, %s, %s,)", d) 

其中 data 是我制作的数组列表,只能为此 json 执行。我需要一个函数来执行我想要的任何 json,它可以在任何键的值中包含 100 个列表元素。

【问题讨论】:

  • 确实需要更多信息。 Postgres 版本? Python版本?什么 Python Postgres 驱动程序?连接代码?将此信息添加到您的问题中。同时看看 Python 中的Json 模块。
  • Postgres 版本为 13。
  • Python 版本是 3.7(我使用的是 pycharm IDE)。这就是我的连接方式: conn = psycopg2.connect(database = "postgres", user = "postgres", password = "hoelscher", host = "localhost", port = "5432") cur = conn.cursor() conn .commit() conn.close() cur.close()
  • cur.execute("CREATE TABLE Table_1(Name varchar, BGE3 varchar, Trans varchar, Art varchar);") for d in data: cur.execute("INSERT into B_Json_3(Name, BGE3, Trans , Art) VALUES (%s, %s, %s, %s,)", d)
  • 其中 data 是我制作的数组列表,只能为此 json 执行。我需要一个函数来执行我想要的任何 json,它可以在任何键的值中包含 100 个列表元素。

标签: python postgresql


【解决方案1】:

建表部分,使用 Python json 模块将 JSON 转换为 Python dict 和 psycopg2.sql 模块动态转换为CREATE TABLE

import json
import psycopg2
from psycopg2 import sql

tbl_json = """{
"Table_1": [
    {
        "Name": "B"
    }, 
    {
        "BGE3": [
            "Itm2", 
            "Itm1", 
            "Glass"
        ]
    }, 
    {
        "Trans": []
    }, 
    {
        "Art": [
            "SYS"
        ]
    }]}
"""
# Transform JSON string into Python dict. Use json.load if pulling from file.
# Pull out table name and column names from dict.
tbl_dict = json.loads(tbl_json)
tbl_name = list(tbl_dict)[0]
tbl_name 
'Table_1'

col_names = [list(col_dict)[0] for col_dict in tbl_dict[tbl_name]]
# Result of above.
col_names
['Name', 'BGE3', 'Trans', 'Art']

# Create list of types and then combine column names and column types into 
# psycopg2 sql composed object. Warning: sql.SQL() does no escaping so potential 
# injection risk.
type_list = ["varchar", "varchar", "varchar"]
col_type = []
for i in zip(map(sql.Identifier, col_names), map(sql.SQL,type_list)):
    col_type.append(i[0] + i[1])
# The result of above.
col_type
[Composed([Identifier('Name'), SQL('varchar')]),
 Composed([Identifier('BGE3'), SQL('varchar')]),
 Composed([Identifier('Trans'), SQL('varchar')])]

# Build psycopg2 sql string using above.
sql_str = sql.SQL("CREATE table {} ({})").format(sql.Identifier(tbl_name), sql.SQL(',').join(col_type) )
con = psycopg2.connect("dbname=test host=localhost user=aklaver")
cur = con.cursor()
# Shows the CREATE statement that will be executed.
print(sql_str.as_string(con))
CREATE table "Table_1" ("Name"varchar,"BGE3"varchar,"Trans"varchar)

# Execute statement and commit.
cur.execute(sql_str)
con.commit()

# In psql client the result of the execute:
 \d "Table_1" 
                   Table "public.Table_1"
 Column |       Type        | Collation | Nullable | Default 
--------+-------------------+-----------+----------+---------
 Name   | character varying |           |          | 
 BGE3   | character varying |           |          | 
 Trans  | character varying |           |          | 



【讨论】:

    猜你喜欢
    • 2021-04-28
    • 1970-01-01
    • 2021-07-19
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    相关资源
    最近更新 更多