I'm constructing json response from data in database using pyodbc. Some of the fields are direct mapping from table column, whereas some of them have to be in list, dict format.
Table structure and data looks like below
custid | custacct | invoiceperiod | amtdue | duedate | charges | balance |col8|col9|col10
abc | 101 | 20190801 | 12 | somedate | 2 | 10 |col8|col9|col10
abc | 101 | 20190701 | 13 | somedate | 3 | 13 |col8|col9|col10
abc | 101 | 20190601 | 10 | somedate | 5 | 11 |col8|col9|col10
custid='abc'
conn = pyodbc.connect(connection_string)
cursor = conn.cursor()
#get all invoiceperiod for custid
l = []
cursor.execute("select invoiceperiod from table where custid=? order by invoiceperiod desc", custid)
rows = cursor.fetchall()
for row in rows:
l.append(row.invoiceperiod)
print("billingperiod:", l)
#get other direct mapping fields from DB
cursor.execute("SELECT col8,col9,col10 FROM table where custid=? and invoiceperiod=(select max(invoiceperiod) from table where custid=?)", custid, custid)
results = []
columns = [column[0] for column in cursor.description]
for row in cursor:
results.append(dict(zip(columns, row)))
# results.append("billingperid", l)
print(results)
For given custid ('abc') expected json response should be as below -
{
"accounts": [{
"custacct": 101,
"invoiceperiods": ["20190801", "20190701","20190601"],
"currentinvoicePeriod": "20190801",
"custacctsummary":{
"amtdue":12,
"duedate":"somedate",
"charges":2,
"balance":10
},
"col8":value1,
"col9":value2,
"col10":value3
}]
}
1] How to construct "custacctsummary" json object and append to json response
2] prepare list of all invoiceperiod for given custid/custacct and append to main json response
3] get value for other attributes for current/latest invoiceperiod.