Home > Enterprise >  I am trying to convert from csv to json and it gives an error because missing values
I am trying to convert from csv to json and it gives an error because missing values

Time:10-30

I am trying to convert from csv to json and it gives an error because reader_row[10] has missing values. How can I replace the missing value to Null? and write.

l = []

with open("data.csv", 'r') as data_file:

    reader = csv.reader(data_file)
    headers = next(reader)
    for reader_row in reader:
        d = {}
        d[headers[11]] = str(reader_row[11])
        d[headers[13]] = str(reader_row[13])
        d[headers[14]] = str(reader_row[14])
        d[headers[18]] = str(reader_row[18])
        d[headers[3]] = int(reader_row[3])
        d[headers[16]] = bool(reader_row[16])
        d[headers[4]] = float(reader_row[4])
        d[headers[5]] = str(reader_row[5])
        d[headers[10]] = int(reader_row[10]) 
        d[headers[17]] = int(reader_row[17])
        d[headers[15]] = int(reader_row[15])
        d[headers[0]]={'Address Street': str(reader_row[0]),
                       'Address City': str(reader_row[1]),
                       'Address Postcode': str(reader_row[2])
                       }
        d[headers[8]]={'Credit Card Number': str(reader_row[8]),
                       'Credit Card Start Date': str(reader_row[6]),
                       'Credit Card Expiry Date': str(reader_row[7]),
                       'Credit Card CVV': int(reader_row[9]),
                       'Bank IBAN' : str(reader_row[12])
                       }
        d[headers[19]]={'Vehicle Make': str(reader_row[19]),
                        'Vehicle Model': str(reader_row[20]),
                        'Vehicle Year': int(reader_row[21]),
                        'Vehicle Type': str(reader_row[22])
                        }
        l.append(d)

CodePudding user response:

You can use a conditional operator to assign None if reader_row[10] is empty.

        d[headers[10]] = int(reader_row[10]) if reader_row[10] else None
  • Related