【问题标题】:How to add data into a json key from a csv file using python如何使用python将数据从csv文件添加到json键中
【发布时间】:2022-01-07 18:59:24
【问题描述】:

我正在尝试将数据从 csv 文件添加到 json 键中并按原样保持原始结构.. json 文件看起来像这样..

{
  "inputDocuments": {
    "gcsDocuments": {
      "documents": [
        {
          "gcsUri": "gs://test/.PDF",
          "mimeType": "application/pdf"
        }
      ]
    }
  },
  "documentOutputConfig": {
    "gcsOutputConfig": {
      "gcsUri": "gs://test"
    }
  },
  "skipHumanReview": false

我尝试加载的 csv 文件具有以下结构..

请注意

模仿类型

不包含在 csv 文件中。

我已经有可以做到这一点的代码,但是它有点手动,我正在寻找一种更简单的方法,它只需要一个包含值的 csv 文件,并且这些数据将被添加到 json 结构中。预期结果应如下所示:

{
      "inputDocuments": {
        "gcsDocuments": {
          "documents": [
            {
              "gcsUri": "gs://sampleinvoices/Handwritten/1.pdf",
              "mimeType": "application/pdf"
            },
            {
              "gcsUri": "gs://sampleinvoices/Handwritten/2.pdf",
              "mimeType": "application/pdf"
            }
          ]
        }
      },
      "documentOutputConfig": {
        "gcsOutputConfig": {
          "gcsUri": "gs://test"
        }
      },
      "skipHumanReview": false

我目前正在使用的代码,有点手动,看起来像这样..

import json

# function to add to JSON
def write_json(new_data, filename='keyvalue.json'):
    with open(filename,'r+') as file:
        # load existing data into a dict.
        file_data = json.load(file)
        # Join new_data with file_data inside documents
        file_data["inputDocuments"]["gcsDocuments"]["documents"].append(new_data)
        # Sets file's current position at offset.
        file.seek(0)
        # convert back to json.
        json.dump(file_data, file, indent = 4)

    # python object to be appended
y = {
          "gcsUri": "gs://test/.PDF",
          "mimeType": "application/pdf"        
    }
    
write_json(y)

【问题讨论】:

    标签: python arrays json csv


    【解决方案1】:

    我会建议这样的事情:

    import pandas as pd
    import json
    from pathlib import Path
    
    df_csv = pd.read_csv("your_data.csv")
    json_file = Path("your_data.json")
    json_data = json.loads(json_file.read_text())
    
    documents = [
        {
            "gcsUri": cell,
            "mimeType": "application/pdf"
        }
        for cell in df_csv["column_name"]
    ]
    json_data["inputDocuments"]["gcsDocuments"]["documents"] = documents
    
    json_file.write_text(json.dumps(json_data))
    

    也许您应该将其拆分为单独的函数,但它应该传达总体思路。

    【讨论】:

    • 获取 column_name 变量的关键错误
    • 您必须使用 csv 中列的名称,而不是 column_name。如果您不使用列标题,您可以在 csv 文件顶部添加一个,例如"gcsUri"。然后将Python代码中的column_name替换为gcsUri
    • 或者,您可以使用pd.read_csv("your_data.csv", header=None, usecols=[X], names=['gcsUri']) 读取csv 数据,并将X 作为包含您要查找的数据的列号。现在您只需阅读该列并将其命名为gcsUri。稍后您可以通过df_csv["gcsUri"] 访问它
    • 这有效.. 只需要定义 column_name 并更改 file_data 以使用 json 从我的文件中读取
    猜你喜欢
    • 2017-03-11
    • 1970-01-01
    • 2022-01-06
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多