【问题标题】:How to use column names when creating JSON object, Python创建 JSON 对象时如何使用列名,Python
【发布时间】:2012-09-04 20:10:54
【问题描述】:

为了提高代码的可读性,我想在创建 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"
    }
]
>>> 

【问题讨论】:

  • 有什么理由不应该使用 DictCursor?只需将光标调用更改为cursor = mydb.cursor(MySQLdb.cursors.DictCursor)

标签: python mysql database json


【解决方案1】:

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

【讨论】:

  • 由于某种奇怪的原因,我在 zip() 末尾收到“无效语法”错误
  • 那是因为行中有一个实际错误,并且过于冗长。我直接通过dict 调用更新了它。
【解决方案2】:
    from django.db import connection

    cursor = connection.cursor()
    cursor.execute("SELECT * FROM blog_contact")
    rows = cursor.fetchall()
    columns = [desc[0] for desc in cursor.description]
    result = []
    for row in rows:
        row = dict(zip(columns, row))
        result.append(row)
    row = {"columns": columns,"rows":rows,"results":result}
    return render(request, 'blog/contact.html', row)

【讨论】:

    猜你喜欢
    • 2019-02-16
    • 1970-01-01
    • 2021-09-28
    • 2017-05-23
    • 1970-01-01
    • 2023-03-06
    • 2018-11-27
    • 2019-06-02
    • 2021-04-13
    相关资源
    最近更新 更多