0

I am trying to look through this:

[
    {"leadID":"1","leadName":"Steve"},
    {"leadID":"2","leadName":"Bob"},
    {"leadID":"3","leadName":"Bill"},
    {"leadID":"4","leadName":"Jim"},
    {"leadID":"5","leadName":"James"},
    {"leadID":"6","leadName":"John"},
    {"leadID":"7","leadName":"Eric"},
    {"leadID":"8","leadName":"Tony"},
    {"leadID":"9","leadName":"Jason"},
    {"leadID":"10","leadName":"Paul"}

]

I am trying to do it using the $.each but I cannot get it right. Here was a test to the console:

$.each(JSON, function(k, v) {

    console.log(v[0]);

});

I am sure I am just not parsing the JSON right but I cannot figure it out. Ultimately I need to append the data to the options of a select input.

Any help on this would be great.

Thanks!

3 Answers 3

4

You need to parse the JSON first, if its not already parsed.

Some browser have this native:

jsonobject = JSON.parse(jsonstring)

If not, you can use jQuery

jsonobject = $.parseJSON(jsonstring)

Then, when it's an object, you can loop through it with $.each

$.each(jsonobject, function(x,v) {
   console.log(v.leadID);
   console.log(v.leadName);
});
Sign up to request clarification or add additional context in comments.

3 Comments

This did it. You are right that I needed to parse the JSON first. It's working perfect now. Thanks!
Cool :) If this is a web page, you should use jQuery $.parseJSON. I don't think IE has the JSON library. Cheers.
Yeah, I am doing it with jQuery. Thanks again.
1

If you use $.each,it would look like this:

$.each(myJSON, function(key, value){
    console.log(value);
    console.log(value['leadID']);
});

You don't need to do value[0]. Here is how I normally do this:

for (var tk in myJSON)
{
    console.log(myJSON[tk]);
    console.log(myJSON[tk]['leadID']);
}

See http://api.jquery.com/each/

1 Comment

Thanks for the help but I looks like my problem was because I was not parsing the JSON first. Thanks
0

in your example k will iterate over the indices of you array (0..9) and v will iterate over the objects..

so for example you could do (comments refer to the first iteration):

$.each(JSON, function(k, v) {

    console.log(k); // 0
    console.log(v); // {"leadID":"1","leadName":"Steve"}
    console.log(v['leadID']); // "1"
    console.log(v['leadName']); // "Steve"

});

1 Comment

Thanks for the help but I looks like my problem was because I was not parsing the JSON first. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.