2012-09-04 33 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'來更新它。 –