为什么这个字符串不能转换成字典?

Why won't this string convert to dict?

我有一个小型 Flask 应用程序,用于从数据库导入作业。我用于导入作业的路径如下(job_details 是表单中每个通过作业的作业的提交按钮):

@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)
...

我想将从 request.form['job_details'] 获得的字符串转换为字典,这样我就可以解析它并通过 job['description'], job['title'] 等访问值。但是,我一直收到 'TypeError: string indices must be integers' 错误。我确定它是作为字符串传递的,据我所知 ast.literal_eval() 应该将字符串转换为字典,但显然不是这样。这是为什么?

来自我的应用程序的一些工作输入示例:

"{'id': 3, 'date': datetime.date(2022, 2, 3), 'job_title': 'Cool title', 'contact_name': 'Mr Cool', 'contact_email': 'coolio@coolcom.cool', '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}"

完整追溯:

return self.wsgi_app(环境,start_response) 文件“”,第 2450 行,在 wsgi_app 响应 = self.handle_exception(e) 文件“”,第 1867 行,在 handle_exception reraise(exc_type, exc_value, tb) 文件“”, 第 39 行,在 reraise raise value 文件“”,第 2447 行,在 wsgi_app 响应 = self.full_dispatch_request() 文件“”,第 1952 行,在 full_dispatch_request rv = self.handle_user_exception(e) 文件“”,第 1821 行,在 handle_user_exception reraise(exc_type, exc_value, tb) 文件“”,第 39 行,在 reraise 中提高值 文件“”,第 1950 行,在 full_dispatch_request rv = self.dispatch_request() 文件“”,第 1936 行,在 dispatch_request return self.view_functionsrule.endpoint 文件“”,第 57 行,在 app 中 if job['listing_type'] == “Basic job listing (free)”:

如果您的申请发回 json,那么您应该 json.loads 而不是 ast.literal_eval

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.

您的字符串包含 datetime.date (datetime.date(2022, 2, 3)),这不是枚举

之一

此后我一直致力于此并解决了这个问题。老实说,我不确定如何。我最终使用了 ast.literal_eval 并且到目前为止它一直有效并且我的程序现在可以正常工作。然而,我没有更改数据库中的 datetime.date 值,尽管将来我认为我会根据经验避免这种类型。

谢谢大家提意见