Maitreyee Tewari
Maitreyee Tewari

Reputation: 99

"List index not in range" error while converting json to csv?

Below is a code suggested by one of the stackoverflow user, I tried running it, but it is returning error. The error could be small , but as I am very new to Python I am unable to correct it. Kindly help. Here is a snippet of json file

[{
    "address": " Karaikudi, Sivagangai-623004", 
    "college": "College (Engineering)", 
    "courses": [], 
    "email": " [email protected], [email protected]", 
    "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": " [email protected], [email protected]", 
    "fax": "044-24502573", 
    "name": "A. J. College Of Pharmacy", 
    "phone": "044-24502572", 
    "recognition": " Dr. Mgr University And Approved By Aicte", 
    "website": "www.msajcpharm.in"
}]

Below is the code:

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)

and following is the error I am encountering:

    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

Upvotes: 1

Views: 150

Answers (1)

Nhor
Nhor

Reputation: 3940

The list in your json is empty:

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

So it's obvious you are getting an IndexError: list index out of range exception. You can fix this with:

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

Upvotes: 1

Related Questions