I am creating a JSON file from a SQL query. But I could not create truly. The problem is there is a “items” object and it has products. But mine create products directly not in “items” objects.
The Code.
JavaScript
x
21
21
1
import json
2
import collections
3
import sqlite3
4
5
conn = sqlite3.connect('database.db')
6
cursor = conn.cursor()
7
cursor.execute("SELECT barcode,listPrice,salePrice FROM productstable")
8
rows = cursor.fetchall()
9
10
objects_list = []
11
for row in rows:
12
d = collections.OrderedDict()
13
d["barcode"] = row[0]
14
d["listPrice"] = row[1]
15
d["salePrice"] = row[2]
16
objects_list.append(d)
17
j = json.dumps(objects_list,indent=4)
18
with open("products.json", "w") as f:
19
f.write(j)
20
conn.close()
21
yields the following JSON object as a result
JavaScript
1
13
13
1
[
2
{
3
"barcode": "1952084972279",
4
"listPrice": 100.5,
5
"salePrice": 99
6
},
7
{
8
"barcode": "1952084972280",
9
"listPrice": 115.3,
10
"salePrice": 100
11
}
12
]
13
while the desired one should be as follows
JavaScript
1
15
15
1
{
2
"items": [
3
{
4
"barcode": "1952084972279",
5
"salePrice": 100.5,
6
"listPrice": 99
7
},
8
{
9
"barcode": "1952084972280",
10
"salePrice": 115.3,
11
"listPrice": 100
12
}
13
]
14
}
15
Advertisement
Answer
define objects_list
as a dictionary instead of a list.
JavaScript
1
3
1
objects_list = {}
2
objects_list["items"] = []
3
And append to the objects_list["items"]
.
JavaScript
1
2
1
objects_list["items"].append(d)
2