簡體   English   中英

使用 python 將 json 數據插入 postgresql 表

[英]insert json data into postgresql table using python

我需要編寫一個自動化的 python 代碼來創建數據庫表,其中列名作為 json 文件中的鍵,列數據應該是這些各自鍵的值。 我的 json 看起來像這樣:

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

我的表名應該是:Table_1。

所以我的列名應該是這樣的:Name | 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 是我制作的 arrays 列表,只能為此 json 執行。 我需要一個 function 來執行我想要的任何 json,它可以在任何鍵的值中包含 100 個列表元素。

The table creation portion, using Python json module to convert JSON to Python dict and psycopg2.sql module to dynamically 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 |           |          | 



暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM