1

I have some info in JSON which is coming from PHP via Ajax

{"5":"rahul","26":"karan","28":"jatin"}

I wants to get key separate which are 5,26,28 and separate name which are rahul,karan,jatin I use this code in java script. But doesn't get result as i want.

for (var key in ajaxresponse) {
    if (ajaxresponse.hasOwnProperty(key)) 
    {
        alert(key + " -> " + JSON.stringify(ajaxresponse[key]));
    }
}
Naresh
  • 2,761
  • 10
  • 45
  • 78

3 Answers3

5

On a really simple level, the for() is using ajaxresponse and the if/alert are using response.

If the code you've pasted the actual code? If so, that could be your problem. :)

Dan
  • 550
  • 3
  • 7
1

follow this post to iterate your json data with the help of jQuery

iterate using jQuery

Community
  • 1
  • 1
K D
  • 5,889
  • 1
  • 23
  • 35
1

Simply use 2 arrays, to get to what you want:

var keys = [], vals = [], key,
ajaxresponse = JSON.parse(ajaxresponse);//parse JSON, which is quite important, too!
for (key in ajaxresponse)
{
    if (ajaxresponse.hasOwnProperty(key))
    {
        keys.push(key);
        vals.push(ajaxresponse[key]);
        console.log(key + '->' + ajaxresponse[key]);//no need to call JSON.stringify on a string
    }
}
console.log(keys.join(', '));//will list all keys, comma-separated
console.log(vals.join(', '));//ditto for values
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
  • Result from your solution 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 {, ", 5, ", :, ", r, a, h, u, l, ", ,, ", 2, 6, ", :, ", k, a, r, a, n, ", ,, ", 2, 8, ", :, ", j, a, t, i, n, k, k, ", } But i need 5,26,28 only and rahul,karan,jatin – Naresh Feb 27 '13 at 10:39
  • You've forgotten to parse the JSON, it would seem: `ajaxresponse = JSON.parse(ajaxresponse);` should precede this code – Elias Van Ootegem Feb 27 '13 at 10:41