Home > OS >  Why won't this string convert to dict?
Why won't this string convert to dict?

Time:02-18

I have a small flask app that I'm using to import jobs from a database. The route I use for importing the jobs is as follows (job_details is a submit button in a form for each individual job that passes the job):

@app.route("/job-import", methods=["POST"])
def job_import():
    if "loggedin" in session:
        if request.method == 'POST':
            job = request.form['job_details']

            # Job comes in string format, therefore needs to be converted to DICT
                job = ast.literal_eval(job)
...

I want to convert the string I get from request.form['job_details'] to a dict so I can then parse it and access the values via job['description'], job['title'] etc. However, I keep getting a 'TypeError: string indices must be integers' error. I am sure it is being passed as a string, and as far as I can find ast.literal_eval() should convert the string to a dict, however this is clearly not the case. Why is this?

Some sample input for a job from my app:

"{'id': 3, 'date': datetime.date(2022, 2, 3), 'job_title': 'Cool title', 'contact_name': 'Mr Cool', 'contact_email': '[email protected]', 'location': 'Coolville', 'expiry_date': datetime.date(2022, 5, 1), 'salary': None, 'twitter': None, 'listing_type': None, 'description': 'a cool job for cool people to do cool things', 'url': 'cooljobs.cool', 'logo': None, 'status': None}"

Full traceback:

return self.wsgi_app(environ, start_response) File "", line 2450, in wsgi_app response = self.handle_exception(e) File "", line 1867, in handle_exception reraise(exc_type, exc_value, tb) File "", line 39, in reraise raise value File "", line 2447, in wsgi_app response = self.full_dispatch_request() File "", line 1952, in full_dispatch_request rv = self.handle_user_exception(e) File "", line 1821, in handle_user_exception reraise(exc_type, exc_value, tb) File "", line 39, in reraise raise value File "", line 1950, in full_dispatch_request rv = self.dispatch_request() File "", line 1936, in dispatch_request return self.view_functionsrule.endpoint File "", line 57, in app if job['listing_type'] == "Basic job listing (free)":

CodePudding user response:

If your application is sending back json then you should json.loads instead of ast.literal_eval.

CodePudding user response:

Why is this?

ast.literal_eval docs

Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, None and Ellipsis.

Your string is holding datetime.date (datetime.date(2022, 2, 3)) which is not one of enumerated

  • Related