首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JSONify列表

JSONify列表
EN

Stack Overflow用户
提问于 2016-12-07 22:33:09
回答 1查看 845关注 0票数 0

我在python中有一个列表:

代码语言:javascript
复制
[["blue1", "blue2", "blue3", "blue4"], ["blue5", "blue6", "blue7", "blue8"], ["blue9", "blue10", "blue11", "blue12"], ["blue13", "blue14", "red", "blue15"]]

当我在这个列表上调用json.dump,然后在javascript中调用JSON.parse时,我不会在javascript中得到等价的列表。有什么建议吗?

在python中,我有dump语句:

代码语言:javascript
复制
test = [["blue1", "blue2", "blue3", "blue4"],["blue5", "blue6", "blue7", "blue8"],["blue9", "blue10", "blue11", "blue12"],["blue13", "blue14", "red", "blue15"]]
        return render_template("game.html", test = test);

在html中,我有:

代码语言:javascript
复制
<!DOCTYPE html>
<html>
<style>
#container {
  width: 400px;
  height: 400px;
  position: relative;
}

</style>
<body>

<div id ="container">
</div>

<script src="https://code.jquery.com/jquery-latest.min.js"></script>

<script src="{{ url_for('static', filename='script.js') }}" test = "{{test|tojson|safe}}"></script>
</body>
</html>

在script.js中,我有:

代码语言:javascript
复制
var board = document.currentScript.getAttribute('test');
console.log(board[0][0]);
console.log(board[0][1]);
console.log(board[0][2]);
console.log(board[0][3]);

控制台返回一个[,然后是三个未定义的

EN

回答 1

Stack Overflow用户

发布于 2016-12-08 13:33:46

您只获得该属性(这是一个字符串),就不会将其解析为数组。所以板只是字符串的第一个字符。使用JSON.parse,

代码语言:javascript
复制
 var board = JSON.parse(document.currentScript.getAttribute('test'));

但是,还有另一个问题:使用|safe模板筛选器关闭自动转义。但是JSON是不安全的,例如它包含"字符。如果HTML读取test="[["blue1"],等,则测试属性值为"[["。所以您也需要删除那个过滤器,这样Django就可以为您转义那些引号了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41028588

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档