Adib February 2016

Processing json where the number of json array is dynamic

I have a json response from php to ajax. The thing is depending on the value entered in a text box the number of json arrays vary. Example: sometimes it may return {"count1":10, "ccc1":30} and sometimes like this {"count1":10, "ccc1":32, "count2":40, "ccc2":123,"count3":32,"ccc3":21}. I extract the value in jquery this way:

success: function(response){
    var count = response.count1;
    //do something
}

But now since the number of counts are different I used a loop. Question is I can figure out how many of them I am receiving but how can I process them? The var count = response.count needs to be specific right? I cannot just concate any strings like this:

var count = 0;    
while(something){
    count = count + 1;
    var str = "count"+count;
    var whatever = response.str;
}

So, can someone please help me with a suitable solution in this case?

Answers


Azim February 2016

Loop through all properties and add them in a variable like following.

var response = { "count1": 10, "ccc1": 32, "count2": 40, "ccc2": 123, "count3": 32, "ccc3": 21 };
var count = 0;
for (var prop in response) {
    if (prop.startsWith('count'))
        count += response[prop];
}
console.log(count);


Achshar February 2016

You are on the right track there. Something like this should work for you.

var i = 1;
while(response['count'+i]) {
    var count = response['count'+i];
    i++;
}

You can access the properties as if they were array indices. so response['count'+i] works.


Bhawin Parkeria February 2016

success: function(response){
var count = response.count1;
    var object = JSON.parse(response);
    alert(object.length);
    for (i = 0; i < object.length; i++) { 
        console.log(object[i]);
    }
}


ZeJur February 2016

To retrieve all values use jQuery $.each function.

var data_tmp = '{"count1":10, "ccc1":32, "count2":40, "ccc2":123,"count3":32,"ccc3":21}';
var data = $.parseJSON(data_tmp);
    

   

 $.each(data, function(k,val){
  if(k.toLowerCase().indexOf("count") >= 0){
      $('.wr').append('<div>' + val + '</div>')
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="wr"></div>

Post Status

Asked in February 2016
Viewed 1,258 times
Voted 5
Answered 4 times

Search




Leave an answer