コードの読みやすさを向上させるために、JSONオブジェクトを作成するときに、インデックス番号の代わりにプレーンワードを使用したいと思います。
これは私のデータベーステーブル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コード:
serg@serg-PORTEGE-Z835:~$ 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"
}
]
>>>