0

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?

2
  • 1
    like this? Commented Aug 7, 2013 at 2:50
  • Almost, but my JSON is a little more complex, and I'm not sure how to handle it Commented Aug 7, 2013 at 2:51

3 Answers 3

1

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")
Sign up to request clarification or add additional context in comments.

5 Comments

That is how I'm getting the results to the .js already. Sorry if that wasn't clear. Does that effect the jquery?
Can you give an example of how you would like the output. I think if we had a better idea of what you are trying to accomplish on the client side we could answer your post more specifically
bcoop713, added a jsfiddle with the exact output your looking for.
Thanks so much. I had been trying to use JSON.parse but that was breaking everything for some reason. Much appreciated.
It's preferable for you to put the relevant portions of the JSFiddle into the answer and keep the JSFiddle as supplementary. That way the next person that visits this question does not have to worry about whether or not JSFiddle is up.
1

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

Comments

1

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
    }
});

Comments

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.