如何将JSON MySQL列查询成字典?

时间:2019-07-11 21:11:21

标签: python json pymysql

我的数据库如下:

CREATE TABLE my_table( irrelevant_column TEXT, json_stuff JSON );
mysql> SELECT * FROM my_table;

+------------------------+-----------------------------------------------+
| irrelevant_column      | json_stuff                                    |
+------------------------+-----------------------------------------------+
| blah blah              | { 'this': 'is my json data' }                 |
| more unrelated stuff   | { 'more': 'of my data in the correct format' }|
+------------------------+-----------------------------------------------+

我正在寻找一种优雅的方法来从MySQL查询JSON数据到字典列表中。

我尝试使用DictCursor

cursor = connection.cursor( pymysql.cursors.DictCursor )
cursor.execute( "SELECT json_stuff FROM my_table" )
rows = cursor.fetchall()

,但不能正确处理JSON列类型。它返回以下内容:

[
  { "json_stuff": "<json_stuff row 1 in string format>" },
  { "json_stuff": "<json_stuff row 2 in string format>" }, 
  etc.
]

我想要

[
  { 'this': 'is my json data' },
  { 'more': 'of my data in the correct format' }, 
  etc.
]

此丑陋且低效的代码有效。

def get_list_of_stuff():
    cursor = connection.cursor()
    cursor.execute( "SELECT json_stuff FROM my_table" )
    rows = cursor.fetchall()
    return [ json.loads( row["json_stuff"] ) for row in rows ]

有人知道一种无需遍历所有行并将每个行解析为JSON的方法吗?

1 个答案:

答案 0 :(得分:0)

MySQL开发人员显然不适合驱动程序在JSON数据类型和Python结构化类型之间自动转换。几年前提交了一个错误报告JSON columns should accept Python dicts as input。它被关闭为“不是错误”,并带有注释:

  

因为JSON不是内置类型(甚至不是Python中的类型)。这种转换不应该在驱动程序中进行,更适合于抽象程度较高的框架。

由于您不使用框架,而只是底层数据库API,因此您需要自己进行解析。

我经常不同意他们的推理,我认为您的期望是合理的。就是这样。