3

I am using jquery to loop through json object... But some how it doesn't seem to work...

Here is my code,

$.ajax({
        type: "GET",  
        url: "/users/",  
     // data: "page="+pageNum,  
        async: false,  
        dataType: 'json',  
        success: function(data){  
//alert("OK AJAX");
           $("#search_btn").remove();
           $('#btnadduser').css('visibility','visible');

$.each(data, function() {
  $.each(this, function(k, v) {
    /// iterate through the objects
            $("#nbody").html("<tr style='background-color:#FFFFFF; font-size:14px;'>             <td>"+data.f.user4.first_name+"</td> <td>"+data.f.user4.last_name+"</td><td>"+data.f.user4.username+"</td> <td>"+data.f.user4.email+"</td> <td>"+data.f.user4.username+"</td> <td>");
              });
           });
        }
    });

when i print the json object in terminal, here is what I get.

{"f": 
     {"user4": {"username": "user4", "first_name": "Alex", "last_name": "kasina", "is_active": true, "email": "alexkasina@gmail.com"},     
      "user5": {"username": "user5", "first_name": "", "last_name": "", "is_active": false, "email": "", }, "user2": {"username":      "user2", "first_name": "", "last_name": "", "is_active": true, "email": ""}, 
      "user3": {"username": "user3", "first_name": "", "last_name": "", "is_active": true, "email": ""}, 
      "user1": {"username": "user1", "first_name": "", "last_name": "", "is_active": true, "email": ""}, 
      "lexx": {"username": "lexx", "first_name": "", "last_name": "", "is_active": true, "email": "tas.ss@df.dc"}}}

I want to iterate through each user setting their first_name, last_name, user_name,... Some help please?

The view

@login_required
def users(request):
    from django.core.serializers.json import DjangoJSONEncoder
    from django.forms.models import model_to_dict

    html = User.objects.all()
    f = {}                # initialise the output
    username = 'username'  # one of the fields from myModel
    [f.update({x[username]: x}) for x in [model_to_dict(y) for y in html]]
    result = simplejson.dumps({"f" : f}, cls=DjangoJSONEncoder)
    print result#To see the json object
return HttpResponse(result)  
garnertb
  • 9,454
  • 36
  • 38
Alexxio
  • 1,091
  • 3
  • 16
  • 38

2 Answers2

1

views.py

@login_required
def users(request):
  from django.core.serializers.json import DjangoJSONEncoder
  from django.forms.models import model_to_dict

  html = User.objects.all()
  f = [model_to_dict(x) for x in html]
  return HttpResponse(simplejson.dumps(f), cls=DjangoJSONEncoder)

javascript:

var user_list = JSON.parse(data);
for(var i=0; i<user_list.length; i++) {
  var user_name = user_list[i]['username'];
  var first_name = user_list[i]['first_name'];
  var last_name = user_list[i]['last_name'];
  // ...
  // do something with user_name, first_name and last_name...
}
Shang Wang
  • 24,909
  • 20
  • 73
  • 94
  • 1
    SyntaxError: JSON.parse: unexpected character [Break On This Error] var user_list = JSON.parse(data)['f']; I understand the data has already been parsed. Is there another way of creating the list? – Alexxio Mar 11 '13 at 18:30
  • 1
    I'm not sure but I think you don't need the DjangoJSONEncoder in views.py. Just result = simplejson.dumps({"f" : f}) should be fine. – Shang Wang Mar 11 '13 at 18:32
  • 1
    When I remove DjangoJSONEncoder, This is the error, datetime.datetime(2013, 3, 4, 0, 30, 3, tzinfo=) is not JSON serializable. Because of the datetime field in the model. – Alexxio Mar 11 '13 at 19:15
  • still the same error, SyntaxError: JSON.parse: unexpected character. from this, http://stackoverflow.com/questions/8524933/json-parse-unexpected-character-error, I see that the data is already parsed. I don't know why that string 'f' in your ans is not working. I used $.each to accomplish it. Thanks a lot. Upvote for the support – Alexxio Mar 11 '13 at 20:07
0

This worked!

  $.each(data, function(index0, l) {

         $.each(l, function(index1, n) {

             /// iterate through the objects

             var first_name = n.first_name;
             var last_name = n.last_name;
             var surname = n.username;

             // do something with user_name, first_name and last_name... 

            $("#nbody").append("<tr> <td>"+ first_name +"</td> <td>"+ last_name +"</td><td>"+ username +"</td> </tr>");

              });
           });
Alexxio
  • 1,091
  • 3
  • 16
  • 38