【发布时间】:2018-08-16 08:51:30
【问题描述】:
来自views.py 我有一本这样的字典:
BgDict = {
'1': '#031B4D',
'0': '',
'3': '#062847',
'2': '#303E4D',
'5': '#115478',
'4': '#00122e',
'7': '#152324',
'6': '#243447',
'8': '#11202F'
}
我想将这个dict BgDict转换为jinja2模板中的Javascript Json Object,所以我的整个代码是这样的
views.py
@app.route('/User/Profile/', methods=['GET', 'POST'])
def getFormUpload():
BgDict = {
'1': '#031B4D',
'0': '',
'3': '#062847',
'2': '#303E4D',
'5': '#115478',
'4': '#00122e',
'7': '#152324',
'6': '#243447',
'8': '#11202F'
}
return render_template("profile.html", BgDict=json.dumps(BgDict))
profile.html
<script>
var bgjson = '{{BgDict|tojson|safe}}';
console.log(jQuery.type(bgjson));
console.log(bgjson[4]); // it should be #00122e but it is :
</script>
从控制台日志来看,它的类型是String,因此bgjson[4] 是: 而不是#00122e。
这是怎么回事?如何从BgDict 中获取json 对象?谢谢。
【问题讨论】:
-
如果您在将
json.dumps(...)传递给模板之前已经在执行它 - 为什么在模板本身中需要|tojson?看起来你想要一个或另一个 - 不是两者兼而有之。还有……你不需要var jsonData = JSON.parse(bgjson)吗? -
@JonClements,我刚刚尝试解决,但即使我删除了
|tojson,它仍然无法正常工作,它仍然是一样的。谢谢 -
您是否使用
JSON.parse(...)将字符串变成了一个对象? -
@JonClements,是的,是的,
JSON.parse(bgson)现在我可以获得json对象及其值。非常感谢您的帮助:)