Skip to main content
 首页 » 编程设计

python之在 web2py 中将 db 数据转换为 json 以使用 flot.js 进行可视化

2025年05月04日35oomusou

我在从 web2py 中的数据库数据中获取用于 flot.js 可视化的有效 json 字符串时遇到问题。

这是我的 Controller Action :

def getdata(): 
    return dict(data=db().select(db.realtimedata.id, db.realtimedata.FlowRate, limitby=(0, 3), orderby=~db.realtimedata.id)) 

通用 json View 为 getdata 操作返回此 json 字符串:

{"data": [{"id": 1, "FlowRate": 373}, {"id": 2, "FlowRate": 379}, {"id": 3, "FlowRate": 376}]} 

我怎样才能得到这个json字符串?

[[1,373],[2,379],[3,376]] 

请您参考如下方法:

import json 
 
def getdata(): 
    rows = db().select(db.realtimedata.id, db.realtimedata.FlowRate, 
                       limitby=(0, 3), orderby=~db.realtimedata.id) 
    return json.dumps([[r.id, r.FlowRate] for r in rows]) 

注意,上面直接返回一个字符串,所以不会调用 View 。