python - 在python中将SQL表作为JSON返回

标签 python sql json

我正在使用 web.py 中的一个小网络应用程序,并且正在设置一个 URL 以返回一个 JSON 对象。使用 python 将 SQL 表转换为 JSON 的最佳方法是什么?

最佳答案

这是a pythonic way to do that 的一个非常好的例子:

import json
import psycopg2

def db(database_name='pepe'):
    return psycopg2.connect(database=database_name)

def query_db(query, args=(), one=False):
    cur = db().cursor()
    cur.execute(query, args)
    r = [dict((cur.description[i][0], value) \
               for i, value in enumerate(row)) for row in cur.fetchall()]
    cur.connection.close()
    return (r[0] if r else None) if one else r

my_query = query_db("select * from majorroadstiger limit %s", (3,))

json_output = json.dumps(my_query)

你得到一个 JSON 对象数组:

>>> json_output
'[{"divroad": "N", "featcat": null, "countyfp": "001",...

或使用以下内容:

>>> j2 = query_db("select * from majorroadstiger where fullname= %s limit %s",\
 ("Mission Blvd", 1), one=True)

你得到一个 JSON 对象:

>>> j2 = json.dumps(j2)
>>> j2
'{"divroad": "N", "featcat": null, "countyfp": "001",...

关于python - 在python中将SQL表作为JSON返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3286525/

相关文章:

python - 在python中更改导入名称

php - MySQL 显示多对多关系的结果

php - 查询 MySQL 表中的多列 (PHP)

json - 使用 Go 在 JSON 中解析包含 unicode 字符的键

javascript - 显示 JSON 数据

python matplotlib 极坐标图

python - 核心文件属于哪个可执行文件?

python - 从使用命令行选项解析的 python 脚本启动 ipython shell

java - 以JSP形式接受SQL查询

java - Realm RecyclerAdapter 返回单个项目