在Python中将SQL转换为json

2024-06-24 13:30:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要传递一个可以使用$.parseJSON转换的对象。查询如下所示:

cursor.execute("SELECT earnings, date FROM table")

为了传递可以转换为json的HttpResponse对象,我需要从这里做什么?


Tags: 对象fromjsonexecutedatetableselectcursor
2条回答

你调查过json library吗?

下面将把数据库输出序列化为json。我不确定您的数据是什么样子的,或者您需要json是什么样子的,但是如果您记住python列表->;数组和python dict->;对象,我想您会没事的。

import json
json.dumps(data)

好吧,如果你这么做:

json_string = json.dumps(cursor.fetchall())

你会得到一个数组。。。

[["earning1", "date1"], ["earning2", "date2"], ...]

另一种方法是:

json_string = json.dumps(dict(cursor.fetchall()))

这将给您一个json对象,earnings作为索引。。。

{"earning1": "date1", "earning2": "date2", ...}

如果这不是你想要的,那么你需要指定你想要的结果是什么样子的。。。

相关问题 更多 >