1

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.

4
  • 1
    If you're already doing json.dumps(...) before passing it to the template - why do you need |tojson in the template itself? Looks like you want one or the other - not both. Also... don't you need a var jsonData = JSON.parse(bgjson) in there? Commented Aug 16, 2018 at 8:55
  • @JonClements, I just tried working around, but it still does not work even I removed |tojson, it was still the same. Thanks Commented Aug 16, 2018 at 8:59
  • 1
    And did you do JSON.parse(...) to actually make the string an object? Commented Aug 16, 2018 at 9:00
  • @JonClements, ah yeah it is,JSON.parse(bgson) now I can get json object and its value. Thanks so much for your help :) Commented Aug 16, 2018 at 9:06

1 Answer 1

3

Use JSON.parse method

<script>
    var bgjson = {{BgDict|tojson|safe}};
    console.log(jQuery.type(bgjson));
    console.log(JSON.parse(bgjson)[4]);
</script>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.