gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:35:02 26 4
gpt4 key购买 nike

我的数据库是这样的:

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 即可执行此操作的方法吗?

最佳答案

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

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.

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

就我个人而言,我不同意他们的推理,我认为您的期望是合理的。但事实就是如此。

关于python - 如何将 JSON MySQL 列查询到字典中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56997346/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com