1 回答

TA贡献1805条经验 获得超9个赞
您可以将列表转换为 dict,然后在将其传回之前将其解析为 JSON 字符串。
// These are the names of the columns in your database
>>> column_names = ["storeid", "address", "etc"]
// This is the data coming from the database.
// All data is passed as you are using SELECT * in your query
>>> data = [42, "1 the street", "blah"]
// This is a quick notation for creating a dict from a list
// enumerate means we get a list index and a list item
// as the columns are in the same order as the data, we can use the list index to pull out the column_name
>>> datadict = {column_names[itemindex]:item for itemindex, item in enumerate(data)}
//This just prints datadict in my terminal
>>> datadict
我们现在有一个包含您的数据和列名的命名字典。
{'etc': 'blah', 'storeid': 42, 'address': '1 the street'}
现在将 datadict 转储为字符串,以便将其发送到前端。
>>> import json
>>> json.dumps(datadict)
dict 现在已转换为字符串。
'{"etc": "blah", "storeid": 42, "address": "1 the street"}'
这不需要更改您的数据库,但脚本需要知道列名或使用某些 SQL 动态检索它们。
如果数据库中的数据格式正确,可以传递给前端,那么您不需要更改数据库结构。如果它的格式不正确,那么您可以更改它的存储方式或更改您的 SQL 查询来操作它。
添加回答
举报