I'm sending the below string to a django template.
<script>
var data = '[{"a": 0}, {"b": 1}]'
</script>
- How do I get keys as
["a", "b"]using javascript - Also I need a javascript function to retrieve a value for a given key.
I'm sending the below string to a django template.
<script>
var data = '[{"a": 0}, {"b": 1}]'
</script>
["a", "b"] using javascriptYou need to convert the python object into a format that javascript can understand, i.e json. To do so, use simplejson in your view:
from django.utils import simplejson
from django.shortcuts import render
def some_view(request):
...
python_data = [
{ 'a' : 'foo', 'b' : 'bar' },
...
]
json_data = simplejson.dumps(python_data)
render(request, "some_template.html", { 'data' : json_data })
and in your template:
<script>
var data = {{ data|safe }}
</script>
(Simplejson is fine for converting normal python objects. If you want to convert a QuerySet though, you need to use Django's serialisers)
Why don't you return JSON?
from django.utils import simplejson
def function(request):
if not request.is_ajax():
raise Http404
data = list(
dict(
a=0,
b=1
)
)
return HttpResponse(simplejson.dumps(data), mimetype='application/json')
javascript (using jquery in this example)
function getData(){
$.ajax({
type: "GET",
url: "/your/url/to/function/",
success: function(data){
return data;
}
});
}
var data = getData();
How do I get keys as ["a", "b"] using javascript
var arrMain = [{"a": 2}, {"b": 3}],
arrKey = [];
for (key in arrMain) {
if (arrMain.hasOwnProperty(key)) {
arrKey.push(Object.keys(arrMain[key])[0]);
}
}
console.log(JSON.stringify(arrKey)); // returns ["a","b"]
Also I need a javascript function to retrieve a value for a given key.
function returnValueByKey(arrMain, arrKey, lookupKey) {
for (key in arrKey) {
if (arrKey.hasOwnProperty(key) && arrKey[key] === lookupKey) {
return arrMain[key][arrKey[key]];
}
}
}
console.log(returnValueByKey(arrMain, arrKey, 'a')); // returns 2