0

I have a page which displays some data. The data it displays needs to be in JS Array format (representing the python nested list).

In order to do this, I use a JS function that fetches the data from a django view:

js 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 comes back is typeof string, and I thought that I could just use JSON.parse() to pull into a JS Array, however this does not work:

var data = getDataFromFiles1(url);
console.log(data + " : " + typeof data)
data = JSON.parse(data)
console.log(data + " : " + typeof data)

and the logging included above gives:

"[[\"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

Am I missing something obvious? How do I create a JS Array object with this data (with the flexibility of not dropping the data in with template tags on load?

2 Answers 2

2

You don't show your model, but I would guess a.data is already JSON - so you're double-encoding it.

Drop the json.dumps and just return HttpResponse(a.data, content_type="application/javascript").

Sign up to request clarification or add additional context in comments.

1 Comment

this has an advantage over my answer and should be the accepted one: it does not waste a full json.dumps-->JSON.parse cycle!
1

Try to JSON.parse(...) it again. Maybe the Python side is already JSON-encoding it due to content_type="application/javascript".

1 Comment

take a look at Daniel Roseman's answer too, I think that works better!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.