bcoop713
bcoop713

Reputation: 1073

Parse JSON from django with jquery

I'm trying to send data results from django to javascript in JSON through an AJAX call. In django I have the below variable

results = {key1:[1,2,3],
           key2:[[name1,lat1,lng1],[name2,lat2,lng2],[name3,lat3,lng3]]}

I can then successfully return a json dump of results I have verified that the data being captured by my javascript ajaxSuccess function is exactly results

I would like the output to be as follows:

var1 = [1,2,3]
var2 = [name1, lat1, lng1]
var3 = [name2, lat2, lng2]
var4 = [name3, lat3, lng3]

What is the best way to parse the results in javascript and should I reformat it some other way in django first?

Upvotes: 0

Views: 2940

Answers (3)

jhanifen
jhanifen

Reputation: 4591

Based on your update in your question, here is a jsfiddle with the exact output you are looking for.

http://jsfiddle.net/jhanifen/7RfNs/

And a jsfiddle with a loop using jquery

http://jsfiddle.net/jhanifen/7RfNs/1/

Depending on how you want to parse and use the results, try using jquery each as karthikr stated in the comment

http://api.jquery.com/jQuery.each/

As stated in the jquery docs

jQuery.each(obj, function(i, val) {
  $("#" + i).append(document.createTextNode(" - " + val));
});

Also you can use json.dumps in django, which makes it very easy to output json, see this post

Creating a JSON response using Django and Python

return HttpResponse(json.dumps(response_data), mimetype="application/json")

Upvotes: 1

dan-klasson
dan-klasson

Reputation: 14180

Just use ajax():

$.ajax({ 
    type: 'GET', 
    url: 'http://example/foo/', 
    dataType: 'json',
    success: function (data) { 
        console.log(data); // do anything you want with your parsed data
    }
});

Upvotes: 1

Ashis Kumar
Ashis Kumar

Reputation: 6544

You can use JSON.parse(results) and or eval(results) in javascript to parse the result.

Upvotes: 1

Related Questions