简体   繁体   English

Django:使用Javascript数组在模板中解析JSON

[英]Django: Parse JSON in template using Javascript array

In my template I pass parameters in array: technicCategories is array of json_serializer.serialize So I can't to make something like this: var technicCategories = '{{ technicCategories|escapejs }}'; 在我的模板我通过在阵列参数: technicCategories是阵列json_serializer.serialize所以我不能做这样的事情: var technicCategories = '{{ technicCategories|escapejs }}'; because it is array and I tried and it gives me error: " JSON Parse error: Unexpected identifier "u" ", my array looks like: var technicCategories = '[u\'[{"model": "automarket.technicandallf... . 因为它是数组,我试过,它给了我错误:“ JSON Parse error: Unexpected identifier "u" ”,我的数组看起来像: var technicCategories = '[u\'[{"model": "automarket.technicandallf... So i decided to do this: 所以我决定这样做:

for (var i = 0; i < {{ index }}; i++){
            var technicCategories = '{{ technicCategories.i|escapejs }}';
            technicCategories = JSON.parse(technicCategories);
            console.log(technicCategories);
    }

but there is a problem: SyntaxError: JSON Parse error: Unexpected EOF . 但是有一个问题: SyntaxError: JSON Parse error: Unexpected EOF But if I make this: var technicCategories = '{{ technicCategories.0|escapejs }}'; 但如果我这样做: var technicCategories = '{{ technicCategories.0|escapejs }}'; all works fine but gives me only object at index 0. 一切正常,但只给我索引0的对象。

What is in technicCategories ? 什么是技术类别? And why are you only trying to put inside a variable only first value from list? 为什么你只想把列表中的第一个值放入变量?

Try this var technicCategories = '{{ technicCategories|safe }}'; 试试这个var technicCategories = '{{ technicCategories|safe }}';

It should do the trick, and in technicCategories variable, there will be a array of your elements. 它应该做的伎俩,在technicCategories变量中,将有一个元素数组。

You need to serialize the whole data, instead of just the elements of the list. 您需要序列化整个数据,而不仅仅是列表的元素。 So create a list with all the elements you want to serialize, and then serialize the list. 因此,创建一个包含要序列化的所有元素的列表,然后序列化列表。

If that is not possible for some reason, you can iterate through the list in the template. 如果由于某种原因无法实现,您可以遍历模板中的列表。

var technicCategories = '[{% for element in technicCategories %}{{element|safe}}{% if not forloop.last %},{% endif %}{% endfor %}]';

But I really recommend the first approach. 但我真的推荐第一种方法。

Well, I didn't find solution. 好吧,我找不到解决方案。 So I decided to remind my way to do this 所以我决定提醒我这样做

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

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