Python 将的字符串中的词典转换为词典
我在python中使用请求并以以下形式获得字符串输出:Python 将的字符串中的词典转换为词典,python,python-3.x,flask,jinja2,Python,Python 3.x,Flask,Jinja2,我在python中使用请求并以以下形式获得字符串输出: {a:1,b:2,c:3,d:4,e:5} 然后,我使用flask返回输出,并尝试将其转换为html模板中的表 some_output = response.text return render_template('the-template.html', some_output=some_output) 打印一些输出会给出:{“a”:1,“b”:2,“c”:3,“d”:4,“e”:5} 在模板中,我正在尝试: <html>
{a:1,b:2,c:3,d:4,e:5}
然后,我使用flask返回输出,并尝试将其转换为html模板中的表
some_output = response.text
return render_template('the-template.html', some_output=some_output)
打印一些输出会给出:{“a”:1,“b”:2,“c”:3,“d”:4,“e”:5}
在模板中,我正在尝试:
<html>
<body>
<table>
{% for key, value in some_output.items() %}
<tr>
<th> {{ key }} </th>
<td> {{ value }} </td>
</tr>
{% endfor %}
</table>
</body>
</html>
{%表示键,某些_输出中的值。items()%}
{{key}}
{{value}}
{%endfor%}
当我提交页面以获取输出时,会收到以下错误消息:
jinja2.exceptions.UndelineError:“str对象”没有属性“items”
如何将此字符串对象转换为字典,以便将字典转换为模板中的html表???您可以使用
json。加载
将字符串转换为字典对象:
import json
some_output = response.text
return render_template('the-template.html', some_output=json.loads(some_output))
您可以使用
json.loads
将字符串转换为字典对象:
import json
some_output = response.text
return render_template('the-template.html', some_output=json.loads(some_output))
可以只使用
response.json()
并避免导入json模块可以只使用response.json()
并避免导入json模块