开发者

Checking if an element exists in json

using the following feed:

http://api.twitter.com/1/statuses/user_timeline.json?screen_name=microsoft&include_rts=1&count=10

I 开发者_高级运维am successfully able to loop through this to get the details I want to display on my html page.

However, I need to check if retweeted_status.user.profile_image_url exists, and I am not sure how to do that?

Currently I am looping through the data where data is returned by jquery-ajax:

data[i].retweeted_status.user.profile_image_url

if data[i].retweeted_status.user.profile_image_url does not exist, it does not return null or undefined, I just get the following error:

cannot read property 'user' of undefined


That error message suggests that either your data[i] or your retweeted_status is undefined, which means your call to get the json is most likely failing. WHen data is returned from Twitter it will aways have a profile image url, because they show an egg-like image for those with none uploaded. You should put this before your for loop:

if (typeof(retweeted_status) != "undefined")
{
//code for what to do with json here
}


I think it's a good answer:

if('key' in myObj)


if (something !== undefined) {
   ...
}

... or even better:

if (typeof something != "undefined") {
    ...
}


If you are looping and accessing nesting objects:

if(!data)
    return;

while(data.length)
{
    var tweet_data = data.shift();

    /* do some work */

    if(!tweet_data|| !tweet_data.retweeted_status)
        continue;

    var retweeted_status = tweet_data.retweeted_status;

    /* do your other work */
}

This loop no longer needs to use array indexes, which isn't the most efficient unless you specifically need the index for something. Instead, it pops the first element off the array and using that object directly. The loop internals can then check the existence of a property on tweet_data.

I try to avoid using more than 1 level of dereferencing for 2 reasons (like objA.child.property): 1) You can check the existence of an object from the start and if it doesn't exist, jump out or assign default values. 2) Everytime JavaScript needs to access the method property, it first has to find child withing objA and then access property. Could be slow in large loops.


Take a look at $.grep(). It helps you loop through JSON objects. I used it on the link you provided. I used it to loop through the tweets and find the retweeted user images. You can have a look at my code here: http://jsfiddle.net/q5sqU/7/


Another thing you can do, which has worked for me:

if(retweeted_status) {
  // your code
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜