How do I convert a Python dictionary to a JavaScript hash table?

I went to Python regular dictionary pattern and I need inside

$(document).ready(function() {.. }

to convert this Python dictionary to JavaScript dictionary. I tried like

var js_dict={{parameters}};

      

but i got errors ( ' instead of ' and all lines start with u ' ). How do I convert a Python dictionary to a JavaScript hash table?

+6


source to share


8 answers


Python and javascript have different representations of how to represent a dictionary, which means that you need an intermediate representation in order to pass data between them. The most common way to do this is with JSON , which is a simple lightweight data interchange format.



Use the jython python library to convert (or dump) your python python to a JSON string. Then in javascript parse the JSON string into javascript dict. (If you are using JQuery use jQuery.parseJSON )

+15


source


You can convert it to JSON and use it in this template

In your python code do



import json
...
...
return {'parameters': json.dumps(parameters)} #This data goes into your template

      

+6


source


You can use json.dumps(parameters)

withmark_safe()

def custom_view(request):
    ...
    return render(request, 'tmpl.html', {'parameters': mark_safe(json.dumps(parameters))})

      

With mark_safe()

I am getting unescaped code in the template.

+2


source


As others have suggested, converting your dictionary to JSON to your representation and then passing the JSON to the template context is actually your best approach, but if you want to store it as a python dictionary in your template, you can; you just need to manually create the javascript version (i.e. you cannot just dump it with {{ parameters }}

)

<script>
    var js_dict = {
        {% for k, v in parameters %}
        "{{ k }}": "{{ v }}"{% if not forloop.last %},{% endif %}
        {% endfor %}
    }
</script>

      

+1


source


A working example inspired by Chris Patt is below (note the difference):

 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 json lib doesn't work for me when working with variables in a template in Django.

+1


source


You don't need to send a dictionary.

This is how I did it:

views.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):

data: [{% for item in data %}
    { "y": '{{ item.hostelName }}', "a": '{{ item.opi_value }}' }{% if not forloop.last %},{% endif %}
{% endfor %}],

      

0


source


How to handle this case by passing an object in the template page instead of passing the dict from the py file and I created the required dict for the template itself. as:

on my ru:

def abc(request): 
     conf = assessment_master.objects.all()
     return render(request, "enter_scheme.html", {'conf':conf})

      

in my Django template: in my script tag:

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

      

0


source


I found this helps for strings that also contain [']

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)
}

      

0


source







All Articles