I have passed to template regular Python dictionary and I need to inside
$(document).ready(function() {.. }
to convert that Python dictionary to JavaScript dictionary. I tried like
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 ?
Python and javascript both have different representations for a dictionary. So you need an intermediate representation in order to pass data between them. The most commonly used intermediate representation is JSON, which is a simple lightweight data-interchange format. The dumps function converts the dict to a string.
Python dictionaries are implemented as hash tables. Hash tables must allow for hash collisions i.e. even if two distinct keys have the same hash value, the table's implementation must have a strategy to insert and retrieve the key and value pairs unambiguously.
Hash tables or has maps in Python are implemented through the built-in dictionary data type. The keys of a dictionary in Python are generated by a hashing function. The elements of a dictionary are not ordered and they can be changed.
In Python, the Dictionary data types represent the implementation of hash tables. The Keys in the dictionary satisfy the following requirements. The keys of the dictionary are hashable i.e. the are generated by hashing function which generates unique result for each unique value supplied to the hash function.
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.
Use the python json library to 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)
You could convert it to JSON and use that in that template
In your python code do
import json
...
...
return {'parameters': json.dumps(parameters)} #This data goes into your template
You can use json.dumps(parameters)
with 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.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With