使用Python将JSON文件转换为CSV

2024-09-29 21:58:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个JSON文件,如下所示:

{
    "resultSet": {
        "totalRecords": "2",
        "agentLogins": [
            {
                "phoneNumber": "99999",
                "callerId": "999999999",
                "stationId": "99999999",
                "stationName": "",
                "loginDate": "2020-09-17T15:25:34.410Z"
            },
            {
                "phoneNumber": "99999",
                "callerId": "99999999",
                "stationId": "999999",
                "stationName": "",
                "loginDate": "2020-09-17T17:22:48.613Z"
            }
           
        ]
    }
}

我正在尝试使用Python将其转换为CSV文件,以下是我的代码:

import json 
import csv 
  
with open('agentLogins.json') as json_file: 
    data = json.load(json_file) 
  
agentLogins = data['agentLogins']
  
data_file = open('agentLogins.csv', 'w') 
  
csv_writer = csv.writer(data_file) 
  
count = 0
  
for emp in agentLogins: 
    if count == 0: 
  
        header = emp.keys() 
        csv_writer.writerow(header) 
        count += 1
  
    csv_writer.writerow(emp.values()) 
  
data_file.close()


I am getting an error: agentLogins = data['agentLogins'] KeyError: 'agentLogins:'.

If I Remove the first part it works:
    "resultSet": {
        "totalRecords": "2",

我只是想知道我是否可以在不移除任何东西的情况下也让它工作


Tags: 文件csvjsondatacountfilewriterphonenumber
1条回答
网友
1楼 · 发布于 2024-09-29 21:58:10

data['agentLogins']转换为data['resultSet']['agentLogins']即可,这是解决方案:

# Opening JSON file and loading the data  into the variable data 
with open('/content/jsonFile.json') as json_file: 
    data = json.load(json_file) 
  
agentLogins  =  data['resultSet']['agentLogins']
# now we will open a file for writing 
data_file = open('agentLogins.csv', 'w') 
  
# create the csv writer object 
csv_writer = csv.writer(data_file) 


# Counter variable used for writing  
# headers to the CSV file 
count = 0
  
for emp in agentLogins: 
    if count == 0: 
  
        # Writing headers of CSV file 
        header = emp.keys() 
        csv_writer.writerow(header) 
        count += 1
  
    # Writing data of CSV file 
    csv_writer.writerow(emp.values()) 
  
data_file.close() 

相关问题 更多 >

    热门问题