Home > Blockchain >  Python Error when I'm converting Excel to JSON
Python Error when I'm converting Excel to JSON

Time:02-06

Here's my code:

import json, xlrd
import datetime as dt

# This is the Excel data (no keys)
filename=r'C:\Users\timhe\OneDrive\Desktop\people_from_excel.json'

# Open the file (standard file open stuff)
with open(filename, 'r', encoding='utf-8-sig', newline='') as f:
    
    # Load the whole json file into an object named people
    people=json.load(f)
    
    print(people)
    
# Dictionaries are in a list, loop through and display each dictionary.
for p in people:
    name=p['Full Name']
    byear=p['Birth Year']
    
    # Excel date pretty tricky, use xlrd module.
    y, m, d, h, i, s=xlrd.xldate_as_tuple(p['Date Joined'], 0)
    joined=dt.date(y, m, d)
    balance='$' f"{p['Balance']:,.2f}"
    print(f"{name:<22} {byear} {joined:%m/%d/%Y} {balance:>12}")

I converted an Excel data file to JSON and I'm getting this error when I run my code:

TypeError: '<' not supported between instances of 'str' and 'float'

I'm guessing somewhere a data type must change but I'm not sure where I need to make that change.

CodePudding user response:

The error maybe is occurring because the "Birth Year" value in the p dictionary is a float, and you're trying to compare it to a string in the line name=p['Full Name'].

You'll need to cast the birth year to an integer or a string before using it in the comparison.

byear = int(p['Birth Year'])

or

byear = str(p['Birth Year'])
  • Related