Python:JSON 到 CSV

Python: JSON to CSV

我从 Docparser API 收到一个 JSON 文件,我想将其转换为 CSV 文档。

结构如下:

{
  "type": "object",
  "properties": {
    "id": {
      "type": "string"
    },
    "document_id": {
      "type": "string"
    },
    "remote_id": {
      "type": "string"
    },
    "file_name": {
      "type": "string"
    },
    "page_count": {
      "type": "integer"
    },
    "uploaded_at": {
      "type": "string"
    },
    "processed_at": {
      "type": "string"
    },
    "table_data": [
      {
        "type": "array",
        "items": {
          "type": "object",
          "properties": {
            "account_ref": {
              "type": "string"
            },
            "client": {
              "type": "string"
            },
            "transaction_type": {
              "type": "string"
            },
            "key_4": {
              "type": "string"
            },
            "date_yyyymmdd": {
              "type": "string"
            },
            "amount_excl": {
              "type": "string"
            }
          },
          "required": [
            "account_ref",
            "client",
            "transaction_type",
            "key_4",
            "date_yyyymmdd",
            "amount_excl"
          ]
        }

      }
    ]
  }
}

我遇到的第一个问题是如何只使用 table_data 部分?

我的第二个问题是编写允许我将每个部分(即 account_ref、客户端等)放入它们自己的列中的实际代码。我对我的代码进行了很多更改,输出从将属性添加到列中并将 table_data 部分转储到一个单元格中,到仅将 headers 打印到单个单元格中(作为列表)。

这是我当前的代码(无法正常工作):

import pydocparser
import json
import pandas as pd

parser = pydocparser.Parser()
parser.login('API')

data2 = str(parser.fetch("Name of Parser", 'documentID'))
data2 = str(data2).replace("'", '"') # I had to put this in because it kept saying that it needs double quotes.

y = json.loads(str(data2))

json_file = open(r"C:\File.json", "w")
json_file.write(str(y))
json_file.close()
df1 = df = pd.DataFrame({str(y)})
df1.to_csv(r"C:\jsonCSV.csv")

感谢您的帮助!

Pandas 有一个很好的内置函数,叫做 pandas.json_noramlize() 如果您使用的 pandas 版本低于 1.0.0,请使用 pandas.io.json.json_normalize(),它应该可以很好地拆分列。 在这里阅读更多相关信息:

>1.0.0: https://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.io.json.json_normalize.html

=<1.0.0 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.json_normalize.html