所以我已经阅读了很多关于这个主题的先前问题,但没有真正能够帮助我得到我想要的结果所以这里是 CSV 文件示例
tripId,scooterId,userId,totalDuration,pickUpTime,dropOffTime,userLocationAtBooking.0,userLocationAtBooking.1,userLocationAtDropOff.0,userLocationAtDropOff.1,totalFare
18721,927,38579,45,2021-08-22 03:00:49,2021-08-22 03:45:39,24.76412,46.6493,24.76409833,46.64934,9.58
18722,434,38563,45,2021-08-22 03:01:16,2021-08-22 03:45:39,24.76412,46.64933333,24.76407,46.64933333,13.53
18723,876,38554,33,2021-08-22 03:05:57,2021-08-22 03:38:55,24.71392833,46.660645,24.7097,46.66272,0.67
18724,476,32291,65,2021-08-22 03:14:37,2021-08-22 04:18:56,24.77137833,46.64568667,24.7722,46.64523167,32.35
这是所需的输出
{
"38579": {
"18721": {
"scooterId": "927",
"userId": "38579",
"totalDuration": "45",
"pickUpTime": "2021-08-22 03:00:49",
"dropOffTime": "2021-08-22 03:45:39",
"userLocationAtBooking.0": "24.76412",
"userLocationAtBooking.1": "46.6493",
"userLocationAtDropOff.0": "24.76409833",
"userLocationAtDropOff.1": "46.64934",
"totalFare": "9.58"
}
},
"38563": {
"18722" : {
"scooterId": "434",
"userId": "38563",
"totalDuration": "45",
"pickUpTime": "2021-08-22 03:01:16",
"dropOffTime": "2021-08-22 03:45:39",
"userLocationAtBooking.0": "24.76412",
"userLocationAtBooking.1": "46.64933333",
"userLocationAtDropOff.0": "24.76407",
"userLocationAtDropOff.1": "46.64933333",
}
}
}
但这就是我得到的
{
"38563": {
"tripId": "18722",
"scooterId": "434",
"userId": "38563",
"totalDuration": "45",
"pickUpTime": "2021-08-22 03:01:16",
"dropOffTime": "2021-08-22 03:45:39",
"userLocationAtBooking.0": "24.76412",
"userLocationAtBooking.1": "46.64933333",
"userLocationAtDropOff.0": "24.76407",
"userLocationAtDropOff.1": "46.64933333",
"totalFare": "13.53"
}
}
这是我目前正在使用的代码
import csv, json
csvFilePath = 'tripsData.csv'
jsonFilePath = 'tripsData.json'
data = {}
with open(csvFilePath) as csvFile:
csvReader = csv.DictReader(csvFile)
for rows in csvReader:
id = rows['userId']
data[id] = rows
for rows in csvReader:
tripId = rows[tripId]
data[tripId] = rows
with open(jsonFilePath, 'w') as jsonFile:
jsonFile.write(json.dumps(data, indent=4))
任何帮助将不胜感激,请记住我对此很陌生