如何将 JSON MySQL 列查询到字典中?

How to query a JSON MySQL column into a dict?

我的数据库是这样的:

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' }|
+------------------------+-----------------------------------------------+

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

我试过使用 DictCursor

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

但它不能正确处理 JSON 列类型。它returns这个:

[
  { "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 的方法吗?

MySQL 开发人员显然认为驱动程序在 JSON 数据类型和 Python 结构类型之间自动转换是不合适的。几年前提交了错误报告 JSON columns should accept Python dicts as input。它被关闭为 "Not a bug",评论为:

Because JSON is not a built-in type (or even type in Python). This kind of conversions shouldn't be made in a driver, is better suited for frameworks that have an high level of abstraction.

由于您没有使用框架,仅使用 low-level 数据库 API,您需要自己进行解析。

个人而言,我不同意他们的推理,我认为你的期望是合理的。但就是这样。