Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am returning from my django code JSON and it looks like this:

my django code:

objs = AccessInfo.objects.filter(~Q(weblink=''))
return HttpResponse(serializers.serialize('json', objs), mimetype="application/json")

what I get in frontend is:

enter image description here

I want to be able to iterate over those JSON objects in frontend with javascript and show each fields value in some html.

If I alert(data), I am getting [ Object, Object ].

I tried $.parseJSON(data), but i am getting:

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

how can I do it?

UPDATE:

my js is receiving the data like this:

$.ajax({
   url: '/get_book_access_downloads/',
   type: 'get',
   data: {bookid:bookid},
   dataType: 'json'
}).done(function(data){
   // to do
});
share|improve this question

1 Answer 1

up vote 3 down vote accepted

Your data is already parsed. You have a list of JavaScript objects, there is no need to parse it again.

You used jQuery to load the data, and jQuery parses JSON responses for you when you use dataType: 'json' on the $.ajax() call; had you omitted that argument, jQuery would have auto-detected JSON responses by their mime type anyway and decoded for you then too.

See the jQuery.ajax() documentation for the dataType option:

The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

[...]

"json": Evaluates the response as JSON and returns a JavaScript object.

You have a list of 2 results; each result is a JavaScript object with the keys pk, model and fields, and the fields value is another object with each of your model fields.

share|improve this answer
    
thanks. I updated my question, showed how js code gets the JSON objects. how can I access JSON Objects in js. like obj.attribute ? –  doniyor Sep 28 at 9:19
    
@doniyor: obj.fields.attribute, where obj is one of the objects in the data list. –  Martijn Pieters Sep 28 at 9:20
    
but if I do console.log(data.pk); i am getting undefined :( –  doniyor Sep 28 at 9:21
    
@doniyor: you have a list; Use data[0].pk or data[1].pk. –  Martijn Pieters Sep 28 at 9:22
    
oh now working like in fairy tales :)) thanks man. i need to dedicate one full day to study serializing. –  doniyor Sep 28 at 9:24

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.