我寫了一個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)
uj5u.com熱心網友回復:
由于您的帖子沒有提供當前輸出,我剛剛創建了一個 csv 檔案來運行您的代碼:
id,MobileNo
1,923002546363
2,923343676143
3,214134367614
并且作業得很好:
[
{
"id": "1",
"MobileNo": "923002546363"
},
{
"id": "2",
"MobileNo": "923343676143"
},
{
"id": "3",
"MobileNo": "214134367614"
}
]
檢查您的 csv 檔案是否未損壞。如果可能,請使用當前輸出和 csv 檔案編輯您的帖子。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/367348.html
