python - 使用 SQLAlchemy 导入的 Postgresql 数据将 JSON 转换为 Python Dict

标签 python json postgresql dictionary sqlalchemy

关于将 JSON 字符串转换为 Python 数据字典以便在 Pandas 中进行分析,我在这里遇到了一些棘手的问题。我已经阅读了很多关于此的其他问题,但似乎没有一个适合我的情况。

以前,我只是使用 CSV(和 Pandas 的 read_csv 函数)来执行我的分析,但现在我已经开始直接从 PostgreSQL 中提取数据。

我可以毫无问题地使用 SQLAlchemy 连接到我的引擎并运行我的查询。我的整个脚本的运行方式与我从 CSV 中提取数据时的运行方式相同。也就是说,直到它到达我尝试将其中一列(即下面示例文本中的“配置”列)从 JSON 转换为 Python 字典的部分。将其转换为 dict 的最终目标是能够计算“config”列中“options”字段下的响应数。

df = pd.read_sql_query('SELECT questions.id, config from questions ', engine)

df = df['config'].apply(json.loads)

df = pd.DataFrame(df.tolist())

df['num_options'] = np.array([len(row) for row in df.options])

当我运行它时,我收到错误“TypeError: expected string or buffer”。我尝试将“配置”列中的数据从对象转换为字符串,但这并没有解决问题(我收到另一个错误,类似于“ValueError:期待属性名称...”)。

如果有帮助,这里是“配置”列中一个单元格的数据片段(代码应该返回这个片段的结果“6”,因为有 6 个选项):

{"graph_by":"series","options":["Strongbow Case Card/Price Card","Strongbow Case Stacker","Strongbow Pole Topper","Strongbow Base wrap","Other Strongbow POS","None"]}

我的猜测是 SQLAlchemy 在从数据库中提取 JSON 字符串时对它们做了一些奇怪的事情?当我只是从数据库中提取 CSV 时不会发生什么?

最佳答案

在最近的 Psycopg 版本中,Postgresql json(b) 对 Python 的适配是透明的。 Psycopg 是 Postgresql 的默认 SQLAlchemy 驱动程序

df = df['config']['options']

来自Psycopg手册:

Psycopg can adapt Python objects to and from the PostgreSQL json and jsonb types. With PostgreSQL 9.2 and following versions adaptation is available out-of-the-box. To use JSON data with previous database versions (either with the 9.1 json extension, but even if you want to convert text fields to JSON) you can use the register_json() function.

关于python - 使用 SQLAlchemy 导入的 Postgresql 数据将 JSON 转换为 Python Dict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32403978/

相关文章:

python - 使用数组的前一个结果将许多二维数组乘以向量

python - 线程与异步

python - C++:如何检查外部程序是否正在运行?

javascript - 按值降序对 json 进行排序

javascript - 当 key 是变量时无法获取 JSON 值

c# - 通过 Newtonsoft.Json 将 JSON 消息的日期时间数组解析为 C# 时出错

database - Postgres。我可以通过将 BIGINT 切换为 INT 来获得良好的加速吗

postgresql - 如何获得更改运行时参数的权限?

python - 在 django 1.2.1 中,我怎样才能得到类似旧的 .as_sql 的东西?

sql - postgresql 查询