如何在创建JSON对象时使用列名称,Python [英] How to use column names when creating JSON object, Python

查看:151
本文介绍了如何在创建JSON对象时使用列名称,Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了提高我的代码的可读性,我想在创建JSON对象时使用纯文本代替索引数字:

In order to improve readability in my code I want to use plain words instead index numbers, when creating JSON object:

这是我的数据库表school_subjects: p>

this is my database table 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> 

my python code:

my python code:

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"
    }
]
>>> 


推荐答案

游标 object有一个 .description 属性,告诉你每一列的名称,使用它把一行转成一个dict:

The cursor object has a .description attribute that tells you the names of each column, use that to turn a row into a dict:

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规范

这篇关于如何在创建JSON对象时使用列名称,Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆