Home > Back-end >  Date issue, string indices must be integers
Date issue, string indices must be integers

Time:04-07

I am trying to run a project which I did not code my self and I am facing this issue when running the code, I have holidays.json collection: enter image description here

and I have this part of code to parse holidays from this json:

def parse_holidays():
    holidays = db.holidays.find_one({}, {'_id': 0})
    for holiday in holidays:
        holidays[holiday]['date'] = datetime.strptime(holidays[holiday]['date'], '%d/%m/%Y').date()

    return holidays

and I am getting the error:

        holidays[holiday]['date'] = datetime.strptime(holidays[holiday]['date'], '%d/%m/%Y').date() TypeError: string indices must be integers

Any idea how to solve it? the code is in python, using Flask.

CodePudding user response:

holidays[holiday]['date']

holiday value is an object but you are using it as a string to reach a variable. Instead of the way above, you should use the method below.

holiday['date'] = datetime.strptime(holiday['date'], '%d/%m/%Y').date()

CodePudding user response:

db.holidays.find_one() returns a single document of your database. Therefore holidays is a dictionary, e.g { "date": "27/3/2021", "taoz": "friday_holiday_evening" }.

When you loop over it, you're looping over its keys and thus holiday takes the values "date" and "taoz". As a consequence holidays[holiday] is looping over the dictionary values, which are all strings.

holidays[holiday]['date'] is therefore a nonsense, since you're trying to index a string (holidays[holiday]) using a non-numeric index ('date').

In order to make your code working, try to replace find_one with find.

  • Related