【问题标题】:Convert CSV into Json in Python. Format problem在 Python 中将 CSV 转换为 Json。格式问题
【发布时间】:2022-01-04 23:28:03
【问题描述】:

我已经编写了一个 python 代码来将 csv 文件转换为 json 文件。但输出与我想要的不一样。请查看并提出修改建议。

下面是预期的 json 文件。

[
    {
        "id": "1",
        "MobileNo": "923002546363"

    },
    {
        "id": "2",
        "MobileNo": "923343676143"

    }
]

下面是我用python写的代码。

import csv, json 

def csv_to_json(csvFilePath, jsonFilePath):
    jsonArray = []
      
    #read csv file
    with open(csvFilePath, encoding='utf-8') as csvf: 
        #load csv file data using csv library's dictionary reader
        csvReader = csv.DictReader(csvf) 

        #convert each csv row into python dict
        for row in csvReader: 
            #add this python dict to json array
            jsonArray.append(row)
  
    #convert python jsonArray to JSON String and write to file
    with open(jsonFilePath, 'w', encoding='utf-8') as jsonf: 
        jsonString = json.dumps(jsonArray, indent=4)
        jsonf.write(jsonString)
          
csvFilePath = r'my_csv_data.csv'
jsonFilePath = r'data.json'
csv_to_json(csvFilePath, jsonFilePath)

【问题讨论】:

  • 当前输出是多少?
  • 你实际得到了什么输出?旁注:您可以减少对json.dumps() 的调用,然后将jsonf.write() 减少为单个json.dump(jsonf, jsonArray)

标签: python json csv


【解决方案1】:

由于您的帖子没有提供当前输出,我只是创建了一个 csv 文件来运行您的代码:

id,MobileNo
1,923002546363
2,923343676143
3,214134367614

而且效果很好:

[
    {
        "id": "1",
        "MobileNo": "923002546363"
    },
    {
        "id": "2",
        "MobileNo": "923343676143"
    },
    {
        "id": "3",
        "MobileNo": "214134367614"
    }
]

检查您的 csv 文件是否未损坏。如果可能,请使用当前输出和 csv 文件编辑您的帖子。

【讨论】:

  • 谢谢您提供的解决方案运行良好。 :-)
猜你喜欢
  • 2018-03-06
  • 2019-08-15
  • 1970-01-01
  • 2015-03-26
  • 1970-01-01
  • 1970-01-01
  • 2021-03-24
  • 2013-11-07
  • 2020-08-18
相关资源
最近更新 更多