首页 > 解决方案 > 在 Pandas 中扩展 JSON 列

问题描述

我有一个 Excel 表,其中有一列包含类似于下面的 JSON 对象(总是至少有一个项目)。有没有办法用 Pandas 扩展这个专栏?有爆炸功能https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html似乎可以完成工作(结构方面),但没有特殊处理对于 JSON。

[
   {
      "id":1234,
      "title":"SSL Certificate - Signature Verification Failed Vulnerability",
      "rating":"medium",
      "status":"Active"
   },
   {
      "id":5698,
      "title":"SSL Certificate - Subject Common Name Does Not Match Server FQDN",
      "rating":"low",
      "status":"Active"
   }
]

我还尝试了一个 for 循环来实现这一点,这很好,直到我找不到将标准化 JSON 输出连接到“当前行”的方法:

for index, row in filtered.iterrows():
    findings = row["MyJSON_COLUMN"]   
    pd.json_normalize(findings)

标签: pythonjsonexcelpandas

解决方案


您实际上应该使用read_json而不是json_normalize. 请按照以下方式进行。获取所有字符串,将它们保存为 json 文件

{"id":1234,"title":"SSL Certificate - Signature Verification Failed Vulnerability","rating":"medium","status":"Active"}
{"id":5692,"title":"SSL Certificate - Subject Common Name Does Not Match Server FQDN","rating":"low","status":"Active"}

每行的一个字符串。我将它保存为 testingread.json,然后运行它

pd.read_json(r"..../testingread.json", lines=True)

注意lines = true.

在此处输入图像描述


推荐阅读