Python:JSON为CSV

问题描述 投票:0回答:1

我正在从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,client等)放入各自的列中。我对代码进行了很多更改,输出从将属性添加到列中并将table_data部分转储到一个单元格,到仅将标头打印到单个单元格(作为列表)方面有所不同。

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

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")

感谢您的帮助!

python json export-to-csv
1个回答
1
投票

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.0https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.json_normalize.html

© www.soinside.com 2019 - 2024. All rights reserved.