将json转换为csv时出现“列表索引不在范围内”错误?

2024-04-28 01:23:15 发布

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

下面是一个stackoverflow用户建议的代码,我试着运行它,但它返回错误。这个错误可能很小,但由于我对Python非常陌生,所以无法纠正它。请帮忙。 下面是json文件的一个片段

[{
    "address": " Karaikudi, Sivagangai-623004", 
    "college": "College (Engineering)", 
    "courses": [], 
    "email": " contact@accet.net, dptacce@md5.vsnl.net.in", 
    "fax": "04565-224528", 
    "name": "A. C. College Of Engineering & Technology", 
    "phone": "04565-224535, 224528", 
    "recognition": " Madurai Kamaraj University", 
    "website": "www.accet.net"
},{
    "address": " Medabakkam Road, Sholinganallur, Chennai-600119", 
    "college": "College (Pharmacy)", 
    "courses": [
        {
            "brief_details": " Age: 17 years on Dec. 31.", 
            "college_name": "A. J. College of Pharmacy", 
            "course_branch": "B.Pharmacy", 
            "course_duration": " 4-year", 
            "course_nature": " Full-Time", 
            "course_title": "", 
            "course_type": " Medical", 
            "no_of_seats": " 40", 
            "qualifications": " As above Those who have passed Diploma in Pharmacy with 50% (recognized by PCI) are directly admitted in the IInd year of B.Pharmacy.", 
            "selection_process": ""
        }
    ], 
    "email": " contact@accet.net, dptacce@md5.vsnl.net.in", 
    "fax": "044-24502573", 
    "name": "A. J. College Of Pharmacy", 
    "phone": "044-24502572", 
    "recognition": " Dr. Mgr University And Approved By Aicte", 
    "website": "www.msajcpharm.in"
}]

代码如下:

import json
import csv

def write_csv(jsonfile, outfile):

    with open(jsonfile) as f:
        data = json.loads(f.read())

    college_dict = data[0]

    college_keys = list(college_dict.keys())
    college_keys.remove('courses')
    college_keys.remove('college')

    courses_dict = data[0]['courses'][0]
    courses_keys = list(courses_dict.keys())
    courses_keys.remove('brief_details')

    with open(outfile, 'w', newline='') as f:
        csv_writer = csv.writer(f)
        headers = college_keys + courses_keys
        csv_writer.writerow(headers)

        row = (
            [
                college_dict[key] if college_dict[key] else 'NA'
                for key in college_keys
            ] 
            + 
            [
                courses_dict[key] if courses_dict[key] else 'NA'
                for key in courses_keys
            ]
        )

        csv_writer.writerow(row)

jsonfile = '/home/maitreyee/Downloads/SchoolCollege.com/collegesdb/collegesdb1.json'
outfile = '/home/maitreyee/Downloads/SchoolCollege.com/collegesdb/collegesout.csv'

write_csv(jsonfile, outfile)

下面是我遇到的错误:

    maitreyee@Maitreyee:~/Downloads/SchoolCollege.com$ python json2csv4.py
Traceback (most recent call last):
  File "json2csv4.py", line 41, in <module>
    write_csv(jsonfile, outfile)
  File "json2csv4.py", line 15, in write_csv
    courses_dict = data[0]['courses'][0]
IndexError: list index out of range

Tags: ofcsvkeyinjsonnetkeysdict
1条回答
网友
1楼 · 发布于 2024-04-28 01:23:15

json中的列表为空:

...
"courses": [],
...

所以很明显你得到了一个IndexError: list index out of range异常。您可以通过以下方法解决此问题:

courses_dict = data[0]['courses'][0] if data[0]['courses'] else None

相关问题 更多 >