2016-12-07 11 views
0

のリスト:私はこのリストにjson.dumpを呼び出し、JavaScriptでそれをJSON.parseときJSONify私はPythonでリストのリストを持っているリスト

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

、私は同等のリストを得ることはありませんJavaScriptで。助言がありますか? Pythonで

私はダンプ文を持っている:

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

私が持っているscript.jsで
<!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> 

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

コンソールには、[を返し、次に3つの定義されていない

+1

あなたは何を得ることができますか? – TemporalWolf

+1

ダンピングとローディングはどうですか?コードや出力がなければ、 'json.dumps()'と 'JSON.parse' *を使う以外は何も教えてくれません。 –

+0

追加情報を追加しました! – MLE

答えて

0

あなたは属性(文字列)のみを取得し、決して配列に解析しません。したがって、board [0]は文字列の最初の文字にすぎません。使用JSON.parse、

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

はしかし、別の問題がある:あなたは自動エスケープをオフにする|safeテンプレートフィルターを使用しています。しかし、JSON は安全ではありません、例えば"文字が含まれています。あなたのHTMLがtest="[["blue1"],などを読み取る場合、テスト属性の値は"[["です。したがって、Djangoがそれらの引用符をエスケープできるように、そのフィルタも削除する必要があります。

関連する問題