python - 从多个pyodbc数据库查询结果构造一个大的json响应
问题描述
我正在使用 pyodbc 从数据库中的数据构建 json 响应。有些字段是从表列直接映射的,而有些字段必须是列表、字典格式。
表结构和数据如下所示
监护人 | 客户 | 发票期| 到期 | 截止日期 | 收费| 余额 |col8|col9|col10
abc | 101 | 20190801 | 12 | 某天 | 2 | 10 |col8|col9|col10
abc | 101 | 20190701 | 13 | 某天 | 3 | 13 |col8|col9|col10
abc | 101 | 20190601 | 10 | 某天 | 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)
对于给定的 custid ('abc'),预期的 json 响应应如下所示 -
{
"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] 如何构造“custacctsummary”json 对象并附加到 json 响应
2] 准备给定 custid/custact 的所有 invoiceperiod 列表并附加到主 json 响应 3] 获取当前/最新 invoiceperiod 的其他属性的值。
解决方案
您的代码已经生成了一个列表str
print("billingperiod:", l)
# billingperiod: ['20190801', '20190701', '20190601']
和一个包含单个dict
print(results)
# [{'col8': 'value1', 'col9': 'value2', 'col10': 'value3'}]
如果你改变
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)
至 ...
columns = [column[0] for column in cursor.description]
row = cursor.fetchone()
results = dict(zip(columns, row))
print(results)
# {'col8': 'value1', 'col9': 'value2', 'col10': 'value3'}
...将l
列表插入到results
字典中,然后转储到您将得到的 JSON 字符串
results['invoiceperiods'] = l
j = json.dumps(results, indent=4);
print(j)
# {
# "col8": "value1",
# "col9": "value2",
# "col10": "value3",
# "invoiceperiods": [
# "20190801",
# "20190701",
# "20190601"
# ]
# }
您可以使用类似的逻辑来构建其余的 JSON 需求。
推荐阅读
- android - 外层缩放
- ios - 访问数组元素并将其与单元格选定数据匹配
- javascript - 如何在以后的点击事件中访问动态创建的文本节点的值?
- php - 无法使用 PHP 显示来自 Oracle Blob 的图像
- angular - 为 Angular 4 App 编写 jasmine Karma 测试用例的问题
- css - Angular - 覆盖泳道/ngx-datatable 的 CSS
- javascript - 在给定时间内从 n 倒计时到 0,负结束值
- java - Webdriver - 查找具有相同类的第一个 x 元素
- hyperledger-composer - 我们如何将 .bna 文件与根据 byfn.sh 脚本创建的对等节点或通道连接
- angular - Angular 4 webpack 可点击命名空间没有导出的成员插件