From views.py I have a dictionary that is like this:
BgDict = {
'1': '#031B4D',
'0': '',
'3': '#062847',
'2': '#303E4D',
'5': '#115478',
'4': '#00122e',
'7': '#152324',
'6': '#243447',
'8': '#11202F'
}
I would like to convert this dict BgDict to Javascript Json Object in jinja2 template, so my whole code is like this
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>
From console log, its type is String therefore bgjson[4] is : instead of #00122e.
What happened with this? How can I get json object out of BgDict? Thanks.
json.dumps(...)before passing it to the template - why do you need|tojsonin the template itself? Looks like you want one or the other - not both. Also... don't you need avar jsonData = JSON.parse(bgjson)in there?|tojson, it was still the same. ThanksJSON.parse(...)to actually make the string an object?JSON.parse(bgson)now I can getjsonobject and its value. Thanks so much for your help :)