如何将 Python 字典转换为 JavaScript 哈希表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10073564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert Python dictionary to JavaScript hash table?
提问by Damir
I have passed to template regular Python dictionary and I need to inside
我已经传递给模板常规 Python 字典,我需要在里面
$(document).ready(function() {.. }
$(document).ready(function() {.. }
to convert that Python dictionary to JavaScript dictionary. I tried like
将该 Python 字典转换为 JavaScript 字典。我试过
var js_dict={{parameters}};
but I got errors ( 'instead of 'and all strings start with u'). How can I convert Python dictionary to JavaScript hash table ?
但我遇到了错误('而不是'并且所有字符串都以u'开头)。如何将 Python 字典转换为 JavaScript 哈希表?
回答by wdh
Python and javascript both have different ideas about how to represent a dictionary, which means that you need a intermediate representation in order to pass data between them. The most common way to do this is JSON, which is a simple lightweight data-interchange format.
Python 和 javascript 都对如何表示字典有不同的想法,这意味着您需要一个中间表示以便在它们之间传递数据。最常用的方法是JSON,它是一种简单的轻量级数据交换格式。
Use the python json libraryto convert (or dump) your python dict into a JSON string. Then in the javascript parse the JSON string into a javascript dict. (If you are using JQuery, then use jQuery.parseJSON)
使用python json 库将您的 python dict 转换(或转储)为 JSON 字符串。然后在 javascript 中将 JSON 字符串解析为 javascript dict。(如果您使用的是 JQuery,则使用jQuery.parseJSON)
回答by spicavigo
You could convert it to JSON and use that in that template
您可以将其转换为 JSON 并在该模板中使用它
In your python code do
在你的python代码中做
import json
...
...
return {'parameters': json.dumps(parameters)} #This data goes into your template
回答by Vivazzi
You can use json.dumps(parameters)
with mark_safe()
你可以用json.dumps(parameters)
与mark_safe()
def custom_view(request):
...
return render(request, 'tmpl.html', {'parameters': mark_safe(json.dumps(parameters))})
With mark_safe()
I get unescaped code in template.
随着mark_safe()
我在模板中获得未转义的代码。
回答by Hymanstine
I have found that this helps for strings that contain [ ' ] as well
我发现这对包含 [ ' ] 的字符串也有帮助
const convertPythonDictToJSON = function (data) {
let d = data.replace(new RegExp(`(?<=[a-zA-Z])'(?=[a-zA-Z ])`, "g"), '__')
d = d.replace(new RegExp("'", 'g'), '"')
d = d.replace(new RegExp("__", 'g'), "'")
d = d.replace(new RegExp("None", 'g'), 'null')
d = d.replace(new RegExp("False", 'g'), 'false')
d = d.replace(new RegExp("True", 'g'), 'true')
return JSON.parse(d)
}
回答by Chris Pratt
As others have already suggested, converting your dictionary to JSON in your view and then passing the JSON to the template context instead is really your best approach, but if you want to keep it as a python dictionary in your template, you can; you just need to manually create the javascript version (i.e. you can't just dump it with {{ parameters }}
)
正如其他人已经建议的那样,在您的视图中将您的字典转换为 JSON,然后将 JSON 传递给模板上下文确实是您最好的方法,但是如果您想将其作为 Python 字典保留在您的模板中,您可以;你只需要手动创建 javascript 版本(即你不能用 转储它{{ parameters }}
)
<script>
var js_dict = {
{% for k, v in parameters %}
"{{ k }}": "{{ v }}"{% if not forloop.last %},{% endif %}
{% endfor %}
}
</script>
回答by Figo
A working example inspired by Chris Patt's answer below (note the difference):
受 Chris Patt 下面的回答启发的工作示例(注意区别):
42 var js_dict = [
43 {% for k, v in parameters.iteritems %}
44 ["{{ k }}","{{ v }}"] {% if not forloop.last %},{% endif %}
45 {% endfor %}
46 ];
The default python's json lib doesn't seem to work for me when dealing with variables in template in Django.
在 Django 中处理模板中的变量时,默认的 python 的 json 库似乎对我不起作用。
回答by Abhishek Kumar
You don't need to send the dictionary.
您不需要发送字典。
Here is how I implemented this:
这是我如何实现的:
views.py
视图.py
def mess_opi(request):
data = Opi_calculated.objects.all()
return render(request,'hab_app/opi_student_portal.html', {'data': data})
my template(for morris.html):
我的模板(用于 morris.html):
data: [{% for item in data %}
{ "y": '{{ item.hostelName }}', "a": '{{ item.opi_value }}' }{% if not forloop.last %},{% endif %}
{% endfor %}],
回答by Javed
How handled this case by passing object on template page instead on passing the dict from py file and i created the required dict on template itself. like:
如何通过在模板页面上传递对象而不是从 py 文件传递 dict 来处理这种情况,我在模板本身上创建了所需的 dict。喜欢:
on my py:
在我的py上:
def abc(request):
conf = assessment_master.objects.all()
return render(request, "enter_scheme.html", {'conf':conf})
on my django template: within my script tag:
在我的 Django 模板上:在我的脚本标签中:
<script>
var conf_dict_list = {};
{% for obj in conf_dict_list %}
conf_dict_list["{{ obj.short_name }}"] = "{{ obj.select }}"
{% endfor %}
alert(JSON.stringify(conf_dict_list));
// alert('key' in conf_dict_list); to check key is present in dict
</script>