在python中以JSON的forms返回SQL表

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

7 Solutions collect form web for “在python中以JSON的forms返回SQL表”

就我个人而言,我更喜欢SQLObject这种事情。 我修改了一些快速而且脏的testing代码,我必须得到这个:

import simplejson from sqlobject import * # Replace this with the URI for your actual database connection = connectionForURI('sqlite:/:memory:') sqlhub.processConnection = connection # This defines the columns for your database table. See SQLObject docs for how it # does its conversions for class attributes <-> database columns (underscores to camel # case, generally) class Song(SQLObject): name = StringCol() artist = StringCol() album = StringCol() # Create fake data for demo - this is not needed for the real thing def MakeFakeDB(): Song.createTable() s1 = Song(name="B Song", artist="Artist1", album="Album1") s2 = Song(name="A Song", artist="Artist2", album="Album2") def Main(): # This is an iterable, not a list all_songs = Song.select().orderBy(Song.q.name) songs_as_dict = [] for song in all_songs: song_as_dict = { 'name' : song.name, 'artist' : song.artist, 'album' : song.album} songs_as_dict.append(song_as_dict) print simplejson.dumps(songs_as_dict) if __name__ == "__main__": MakeFakeDB() Main() 

这是一个非常好的pythonic方法的例子:

 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",... 
 import sqlite3 import json DB = "./the_database.db" def get_all_users( json_str = False ): conn = sqlite3.connect( DB ) conn.row_factory = sqlite3.Row # This enables column access by name: row['column_name'] db = conn.cursor() rows = db.execute(''' SELECT * from Users ''').fetchall() conn.commit() conn.close() if json_str: return json.dumps( [dict(ix) for ix in rows] ) #CREATE JSON return rows 

调用方法没有JSON …

 print get_all_users() 

打印:

 [(1, u'orvar', u'password123'), (2, u'kalle', u'password123')] 

用json调用方法…

 print get_all_users( json_str = True ) 

打印:

 [{"password": "password123", "id": 1, "name": "orvar"}, {"password": "password123", "id": 2, "name": "kalle"}] 

有关在传输数据之前如何处理数据的更多信息将对您有所帮助。 如果您使用2.6或更新的版本,json模块将提供转储和加载方法: http : //docs.python.org/library/json.html 。

– 编辑 –

不知道你正在使用哪个库,我不能肯定地告诉你,如果你会find这样的方法。 通常,我会像这样处理查询结果(kinterbasdb的例子,因为这是我们目前的工作):

 qry = "Select Id, Name, Artist, Album From MP3s Order By Name, Artist" # Assumes conn is a database connection. cursor = conn.cursor() cursor.execute(qry) rows = [x for x in cursor] cols = [x[0] for x in cursor.description] songs = [] for row in rows: song = {} for prop, val in zip(cols, row): song[prop] = val songs.append(song) # Create a string representation of your array of songs. songsJSON = json.dumps(songs) 

毫无疑问,有更好的专家会有列表parsing,以消除写出循环的需要,但这是有效的,应该是你可以适应任何你正在检索logging的库。

我敲了一个简短的脚本,将所有表中的所有数据转储为列名称的值:值。 与其他解决scheme不同,它不需要关于表或列的信息,它只是查找所有内容并将其转储。 希望有人认为它有用!

 from contextlib import closing from datetime import datetime import json import MySQLdb DB_NAME = 'x' DB_USER = 'y' DB_PASS = 'z' def get_tables(cursor): cursor.execute('SHOW tables') return [r[0] for r in cursor.fetchall()] def get_rows_as_dicts(cursor, table): cursor.execute('select * from {}'.format(table)) columns = [d[0] for d in cursor.description] return [dict(zip(columns, row)) for row in cursor.fetchall()] def dump_date(thing): if isinstance(thing, datetime): return thing.isoformat() return str(thing) with closing(MySQLdb.connect(user=DB_USER, passwd=DB_PASS, db=DB_NAME)) as conn, closing(conn.cursor()) as cursor: dump = {} for table in get_tables(cursor): dump[table] = get_rows_as_dicts(cursor, table) print(json.dumps(dump, default=dump_date, indent=2)) 

我会用psycopg2版本来补充Demz答案:

 import psycopg2 import psycopg2.extras import json connection = psycopg2.connect(dbname=_cdatabase, host=_chost, port=_cport , user=_cuser, password=_cpassword) cursor = connection.cursor(cursor_factory=psycopg2.extras.DictCursor) # This line allows dictionary access. #select some records into "rows" jsonout= json.dumps([dict(ix) for ix in rows]) 

似乎没有人提供直接从Postgresql服务器获取JSON的选项,使用postgres JSONfunctionhttps://www.postgresql.org/docs/9.4/static/functions-json.html

 from django.db import connection sql = 'SELECT to_json(result) FROM (SELECT * FROM TABLE table) result)' with connection.cursor() as cursor: cursor.execute(sql) output = cursor.fetchall() 

一个表如:

 id, value ---------- 1 3 2 7 

将返回一个Python JSON对象

 [{"id": 1, "value": 3},{"id":2, "value": 7}] 

然后使用json.dumps作为JSONstring转储

  • 何时更新时间戳(自动)?
  • sql和mysql有什么区别
  • search表名
  • 左join在哪里条款
  • 如何插入只有默认值的logging?
  • Oracle SQL数据透视表查询
  • SQL Server LIKE包含括号字符
  • SQLpipe理工作室的SQL格式化器
  • SQL SELECT speed int vs varchar
  • 使用sql server 2008中的数据库中的数据备份单个表
  • 在SQL Server中分页结果的最佳方法是什么?