简体   繁体   English

JSONify列表列表

[英]JSONify a list of lists

I have a list of lists in python: 我在python中有一个列表列表:

[["blue1", "blue2", "blue3", "blue4"], ["blue5", "blue6", "blue7", "blue8"], ["blue9", "blue10", "blue11", "blue12"], ["blue13", "blue14", "red", "blue15"]]

When I call json.dump on this list and then JSON.parse it in javascript, I do not get the equivalent list in in javascript. 当我在此列表上调用json.dump然后在javascript中对其进行JSON.parse时,我在javascript中没有得到等效列表。 Any suggestions? 有什么建议么?

In python I have the dumps statement: 在python中,我有dumps语句:

test = [["blue1", "blue2", "blue3", "blue4"],["blue5", "blue6", "blue7", "blue8"],["blue9", "blue10", "blue11", "blue12"],["blue13", "blue14", "red", "blue15"]]
        return render_template("game.html", test = test);

In html I have: 在html中,我有:

<!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>

In script.js I have: 在script.js中,我有:

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]);

Console returns a [, then three undefineds 控制台返回[,然后返回三个未定义

You only get the attribute (which is a string), you never parse it into an array. 您仅获得属性(它是一个字符串),而从未将其解析为数组。 So board[0] is just the first character of the string. 因此,board [0]只是字符串的第一个字符。 Use JSON.parse, 使用JSON.parse,

 var board = JSON.parse(document.currentScript.getAttribute('test'));

However, there is another problem: you use the |safe template filter to turn off auto escaping. 但是,还有另一个问题:您使用|safe模板过滤器来关闭自动转义。 But JSON is not safe , for instance it contains " characters. If your HTML reads test="[["blue1"], et cetera, the value of the test attribute is "[[" . 但是JSON 是不安全的 ,例如它包含"字符”。如果您的HTML读取test="[["blue1"],等,则test属性的值为"[[" So you need to remove that filter too so that Django can escape those quotes for you. 因此,您也需要删除该过滤器,以便Django可以为您转义这些引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM