[英]Read json file to create database in postgres using python
Hi im creating a DB using Python and want to extract the info from this json dict i dont know if it better to extract the info directly from the file:嗨,我正在使用 Python 创建一个数据库,并想从此 json 字典中提取信息,我不知道直接从文件中提取信息是否更好:
data =
{
"b_sales": [{
"position_r": 1,
"position": 1,
"title": "Noda Dorado",
"sales": "A088R7S66W",
"link": "https://www.url.com/nonda-Adapter"
"image": "https://image.jpg",
"price_lower": {
"value": 7.99,
},
"price_upper": {
"value": 10.99,
},
"price": {
"value": 7.99,
}
}, {
"position_r": 2,
"title": "WHOOSH! Kit de limpieza de pantalla",
"sales": "A07ZMFQB2S",
"link": "https://www.url.com/WHOOSH-Screen-",
"image": "https://images.jpg",
"price_lower": {
"value": 15.49,
},
"price_upper": {
"value": 29.99,
},
"price": {
"value": 15.49,
}
}],
"pagination": {
"current_page": 1,
"total_pages": 2
}
}
i already started with the code:我已经开始使用代码:
import psycopg2
conn = psycopg2.connect(
database="postgres", user='postgres', password='password', host='127.0.0.1', port= '5432'
)
conn.autocommit = True
cursor = conn.cursor()
sql ='''CREATE TABLE b_sales (
TITLE CHAR(30) NOT NULL,
SALES CHAR(20),
LINK CHAR(40),
IMAGE CHAR(30),
PRICE_L INT,
PRICE_U INT
PRICE INT
)'''
cursor.execute(sql)
conn.close()
And i dont know how to add the info in the table quite good i tried but without success而且我不知道如何在表格中添加信息很好我试过但没有成功
You can try this solution to insert you data into database您可以尝试此解决方案将数据插入数据库
import psycopg2
connection = conn = psycopg2.connect(
database="postgres", user='postgres', password='password',
host='127.0.0.1', port= '5432'
)
connection.autocommit = True
cursor = connection.cursor()
sql ='''CREATE TABLE b_sales (
TITLE CHAR(30) NOT NULL,
SALES CHAR(20),
LINK CHAR(40),
IMAGE CHAR(30),
PRICE_L INT,
PRICE_U INT,
PRICE INT
)'''
cursor.execute(sql)
connection.close()
def insert_data_into_db(TITLE,SALES, LINK, IMAGE, PRICE_L, PRICE_U,
PRICE):
import psycopg2
connection = psycopg2.connect(
database="postgres", user='postgres', password='password',
host='127.0.0.1', port= '5432'
)
try:
cursor = connection.cursor()
cursor.execute(
"INSERT INTO b_sales(TITLE, SALES, LINK, IMAGE, PRICE_L,
PRICE_U, PRICE) VALUES(%s, %s, %s, %s, %s, %s, %s)",
(TITLE,SALES, LINK, IMAGE, PRICE_L, PRICE_U, PRICE)
)
connection.commit()
except Exception as e:
print (e.message)
finally:
connection.close()
for item in data.get("b_sales"): # your python json data
TITLE = item.get("title", "")
SALES = item.get("sales", "")
LINK = item.get("link", "")
IMAGE = item.get("image", "")
PRICE_L = item.get("price_lower", {}).get("value", 0)
PRICE_U = item.get("price_upper", {}).get("value", 0)
PRICE = item.get("price", {}).get("value", 0)
# Inserting data into db
insert_data_into_db(TITLE, SALES, LINK, IMAGE, PRICE_L,
PRICE_U, PRICE)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.