2012-09-04 14 views
1

为了提高可读性,在我的代码,我想用通俗的语言,而不是索引号,创建JSON对象时:如何使用创建JSON对象时,列名,Python的

这是我的数据库表school_subjects:

mysql> DESCRIBE school_subjects; 
+------------------+--------------+------+-----+---------+----------------+ 
| Field   | Type   | Null | Key | Default | Extra   | 
+------------------+--------------+------+-----+---------+----------------+ 
| id    | int(11)  | NO | PRI | NULL | auto_increment | 
| name    | varchar(500) | NO |  | NULL |    | 
| user_id   | int(11)  | NO | MUL | NULL |    | 
| created_by  | varchar(64) | NO |  | NULL |    | 
| created_time  | datetime  | NO |  | NULL |    | 
| num_of_followers | int(11)  | NO |  | NULL |    | 
+------------------+--------------+------+-----+---------+----------------+ 
6 rows in set (0.00 sec) 

mysql> 

我的Python代码:

[email protected]:~$ python 
Python 2.7.2+ (default, Oct 4 2011, 20:03:08) 
[GCC 4.6.1] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import simplejson as json 
>>> import MySQLdb 
>>> import collections 
>>> 
>>> mydb = MySQLdb.connect(host='localhost', user='root', passwd='', db='schooldb') 
>>> cursor = mydb.cursor() 
>>> cursor.execute(""" 
...      SELECT id, name 
...      FROM school_subjects 
...    """) 
6L 
>>> rows = cursor.fetchall() 
>>> result = [] 
>>> for row in rows: 
...  d = dict() 
...  d['id'] = row.id  #I want something similar to this 
...  d['name'] = row.name #but it doesn't work 
...  result.append(d) 
... 
Traceback (most recent call last): 
    File "<stdin>", line 2, in <module> 
AttributeError: 'tuple' object has no attribute 'id' 

,你可以看到我得到这个错误:

Traceback (most recent call last): 
    File "<stdin>", line 2, in <module> 
AttributeError: 'tuple' object has no attribute 'id' 

但是这个代码工作正常:

>>> result = [] 
>>> for row in rows: 
...  d = dict() 
...  d['id'] = row[0] 
...  d['name'] = row[1] 
...  result.append(d) 
... 
>>> subjects = json.dumps(result, indent=4) 
>>> print subjects 
[ 
    { 
     "id": 1, 
     "name": "Math 140" 
    }, 
    { 
     "id": 2, 
     "name": "English 102" 
    }, 
    { 
     "id": 3, 
     "name": "CS 240" 
    }, 
    { 
     "id": 4, 
     "name": "CS 210" 
    }, 
    { 
     "id": 5, 
     "name": "Math 140" 
    }, 
    { 
     "id": 6, 
     "name": "English 102" 
    } 
] 
>>> 
+0

任何你不应该使用DictCursor的原因?只要将你的游标调用改为'cursor = mydb.cursor(MySQLdb.cursors.DictCursor)'。 –

回答

6

cursor对象有一个.description属性,它告诉你每一列的名称,用它来把一行到一个字典:

cursor.execute(""" 
        SELECT id, name 
        FROM school_subjects 
      """) 
columns = [desc[0] for desc in cursor.description] 
result = [] 
for row in rows: 
    row = dict(zip(columns, row)) 
    result.append(row) 

有关.description属性的详细信息,请参阅Python DB API 2.0 specification

+0

非常感谢你! – Vor

+0

由于某些奇怪的原因,我在zip() –

+0

的末尾出现'invalid syntax'错误。这是因为该行中存在实际的错误,并且过于冗长。我用一个直接的'dict'来更新它。 –