【问题标题】:How to convert CSV file to a specific JSON format with nested objects?如何将 CSV 文件转换为具有嵌套对象的特定 JSON 格式?
【发布时间】:2023-03-08 02:19:01
【问题描述】:

我想用 CSV 文件中的数据填充我的 json 消息。我希望每一行都是一个“新”的 json 对象。我正在使用 Python,完成后会将代码连接到 API。一些数据需要归类在“personalinfo”和“carinfo”下,我需要在正确的类别下填充正确的数据,如下面的“预期的 json 消息输出”。

这是我目前所拥有的:

import csv
import json

csvfile = open('test.csv', 'r')
jsonfile = open('file.json', 'w')

fieldnames = ("firstname","r", "lastname","r", "age","r", "gender","r",
              "model","r", "price","r", "loan","r")
reader = csv.DictReader(csvfile, fieldnames)
out = json.dumps( [ row for >row in reader ] )
jsonfile.write(out)

我不知道如何添加“个人信息”和“汽车信息”这两个类别。

示例 csv 表:

 FirstName  LastName    Age gender  Car model Price loan
    Anna    Andersson   28  F       Audi    A8 40    FALSE

预期的 json 消息输出:

{
    "personalinfo": {
        "firstname": "Anna",
        "lastname": "Andersson",
        "age": "28",
        "gender": "F",

        "carinfo": [{
            "car": "Audi",
            "model": "A8"
        }],

        "price": 40,
        "loan": "FALSE"
    }
}

下一条记录应该是一个新的 json 对象。

【问题讨论】:

  • 您有没有尝试过或要求我们为您做?
  • 嗯...该输出不是有效的 JSON...您在这方面走了多远,您的源数据是 pandas DataFrame 还是您呈现数据的方式?
  • @johnashu 添加了代码
  • 我认为 Anna 和 Bea 不会掉以轻心,因为您已经为他们设定了价格并让他们可以出借。也许您应该将这些财产转移到他们的汽车上? “car”也不是一个有效的json标识符,你需要去掉空格。
  • @IgnacioVazquez-Abrams 我试过了,请看添加的代码

标签: python json csv


【解决方案1】:

您需要将 csv 文件中的每一行数据转换为按照您描述的方式布局的 JSON 对象。这可以通过调用单个函数来完成,该函数使用 csv.DictReader 从 csv 文件中获取 row 字典并执行此操作:

import csv
import json

def make_record(row):
    return {
               "personalinfo": {
                   "firstname": row["FirstName"],
                   "lastname": row["LastName"],
                   "age": row["Age"],
                   "gender": row["gender"],
                   "carinfo": [
                       {
                           "car": row["Car"],
                           "model": row["model"]
                       }
                   ],
                   "price": int(row["Price"]),
                   "loan": row["loan"]
               }
           }


with open('csv_test.csv', 'r', newline='') as csvfile, \
     open('json_file.json', 'w') as jsonfile:
    reader = csv.DictReader(csvfile, delimiter='\t')
    out = json.dumps([make_record(row) for row in reader], indent=4)
    jsonfile.write(out)

# Show results.
with open('json_file.json', 'r') as jsonfile:
    print('results:')
    print(json.dumps(json.load(jsonfile), indent=4))

【讨论】:

    猜你喜欢
    • 2019-05-28
    • 2016-11-06
    • 2021-10-29
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-26
    相关资源
    最近更新 更多