【发布时间】:2021-06-10 13:08:02
【问题描述】:
我正在从 SQL 查询创建一个 JSON 文件。但我无法真正地创造。问题是有一个“项目”对象,它有产品。但我的不是直接在“项目”对象中创建产品。
守则。
import json
import collections
import sqlite3
conn = sqlite3.connect('database.db')
cursor = conn.cursor()
cursor.execute("SELECT barcode,listPrice,salePrice FROM productstable")
rows = cursor.fetchall()
objects_list = []
for row in rows:
d = collections.OrderedDict()
d["barcode"] = row[0]
d["listPrice"] = row[1]
d["salePrice"] = row[2]
objects_list.append(d)
j = json.dumps(objects_list,indent=4)
with open("products.json", "w") as f:
f.write(j)
conn.close()
作为结果产生以下 JSON 对象
[
{
"barcode": "1952084972279",
"listPrice": 100.5,
"salePrice": 99
},
{
"barcode": "1952084972280",
"listPrice": 115.3,
"salePrice": 100
}
]
而想要的应该如下
{
"items": [
{
"barcode": "1952084972279",
"salePrice": 100.5,
"listPrice": 99
},
{
"barcode": "1952084972280",
"salePrice": 115.3,
"listPrice": 100
}
]
}
【问题讨论】:
-
谢谢你,亲爱的巴巴罗斯·霍卡姆。您使问题易于理解。
-
不客气,兄弟 :)