把字典转换成Javascript JSON对象?

2024-10-01 09:28:48 发布

您现在位置:Python中文网/ 问答频道 /正文

views.py我有一本这样的字典:

BgDict = {
            '1': '#031B4D', 
            '0': '', 
            '3': '#062847', 
            '2': '#303E4D', 
            '5': '#115478', 
            '4': '#00122e', 
            '7': '#152324', 
            '6': '#243447', 
            '8': '#11202F'
        }

我想将dictBgDict转换成jinja2模板中的Javascript Json对象,所以我的整个代码如下所示

视图.py

^{pr2}$

配置文件.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]:,而不是{}。在

怎么回事?如何从BgDict中获取{}对象?谢谢。在


Tags: 对象pylog模板jsonjinja2字典script