2

I have a POST request which receives a JSON String as a result. The fields, the values, or how deep the array is? These all are unknown. So, I need to loop through each of the json value, its index and its value and perform actions based on it.

$.post(
    "test.php", 
    { action: 'someaction', param: '2' },
    function(data) {
      //now data is a json string
      $.each(data, function() {
       key = data.key; //i need to retrieve the key
       value = data.value; //i need to retrieve the value also

       //now below here, I want to perform action, based on the values i got as key and values
      }
    },
    "json"
);

How can i get the values of JSON seperated as key and value?

Starx
  • 77,474
  • 47
  • 185
  • 261

3 Answers3

5

Sorry, guys, but I solved it myself. Please dont be angry with me. (I will delete the question if it is required by the community.)

$.post(
    "test.php", 
    { action: 'someaction', param: '2' },
    function(data) {
      //now data is a json string
      $.each(data, function(key,value) {
       alert(key+value);
       //now below here, I want to perform action, based on the values i got as key and values
      }
    },
    "json"
);
Starx
  • 77,474
  • 47
  • 185
  • 261
3

Well, JSON gets parsed into JavaScript objects. You can traverse them using for...in:

for(var key in data) {
    if(data.hasOwnProperty(key)) {
        var value = data[key];
    }
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

This will help: Iterating a JavaScript object's properties using jQuery

Community
  • 1
  • 1
Mike Thomsen
  • 36,828
  • 10
  • 60
  • 83