On my website, I have a feature that displays data in JavaScript Array format, representing a nested list in Python.
To achieve this, I utilize a JavaScript function that retrieves the data from a Django view:
JavaScript function:
var getDataFromFiles1 = function(theUrl) {
$.ajaxSetup({async: false});
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send( null );
return xmlHttp.responseText;
};
views.py:
a = MyModel.objects.get(c=b, x=y)
json_object = json.dumps(a.data)
return HttpResponse(json_object, content_type="application/javascript")
However, the data that is returned is considered a string by the typeof
operator. Trying to use JSON.parse()
to convert it into a JavaScript Array does not yield the desired outcome:
var data = getDataFromFiles1(url);
console.log(data + " : " + typeof data)
data = JSON.parse(data)
console.log(data + " : " + typeof data)
The resulting logs show:
"[[\"example\", \"example\", \"example\", \"example\", \"not set\"], [\"example\", \"example\", \"example\", \"example\", \"not set"]]" : string
and
[["example", "example", "example", "example", "not set"], ["example", "example", "example", "example", "not set"]] : string
Is there something obvious that I am overlooking? How can I properly create a JavaScript Array object using this data, without relying on template tags during page load?