【发布时间】:2019-11-21 15:41:12
【问题描述】:
我的数据库如下所示:
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 的方法?
【问题讨论】:
-
您是否尝试将 JSON 内容作为字符串获取,然后通过
json模块读取? -
@GreenCloakGuy 这就是最终代码 sn-p 所做的。
-
this和more是json_stuff列中 JSON 数据中的键。 -
我添加了一个内联数据样本。
-
它只多出一行,这在我的书中并不“丑陋”。就编写它所花费的时间而言,它相当有效。请说明您的要求。