2

I have an API I am using to grab results. When It gets results I get something like this back:

{"currentPage":1,"numberOfPages":1,"totalResults":1,"data":[{"id":"Sf8xxo","name":"The Bear Reader Huckleberry Oatmeal Stout","nameDisplay":"The Bear Reader Huckleberry Oatmeal Stout","abv":"6.3","ibu":"33","styleId":21,"isOrganic":"N","status":"verified","statusDisplay":"Verified","createDate":"2015-03-22 17:35:03","updateDate":"2015-03-22 17:35:03","style":{"id":21,"categoryId":1,"category":{"id":1,"name":"British Origin Ales","createDate":"2012-03-21 20:06:45"},"name":"Oatmeal Stout","shortName":"Oatmeal Stout","description":"Oatmeal stouts include oatmeal in their grist, resulting in a pleasant, full flavor and a smooth profile that is rich without being grainy. A roasted malt character which is caramel-like and chocolate-like should be evident - smooth and not bitter. Coffee-like roasted barley and roasted malt aromas (chocolate and nut-like) are prominent. Color is dark brown to black. Bitterness is moderate, not high. Hop flavor and aroma are optional but should not overpower the overall balance if present. This is a medium- to full- bodied beer, with minimal fruity esters. Diacetyl should be absent or at extremely low levels. Original gravity range and alcohol levels are indicative of English tradition of oatmeal stout.","ibuMin":"20","ibuMax":"40","abvMin":"3.8","abvMax":"6","srmMin":"20","srmMax":"20","ogMin":"1.038","fgMin":"1.008","fgMax":"1.02","createDate":"2012-03-21 20:06:45","updateDate":"2015-04-07 15:22:53"},"breweries":[{"id":"m2lpu3","name":"Timeless Pints Brewing Company","description":"Lakewood's first microbrewery! \r\n\r\nOn Father's Day, several years ago, my son and I purchased a home brewing kit for my husband. As an Engineer and a lover of craft beer, he was excited to experiment with his own concoctions. Since his first trial run, he's produced multiple variety of stouts, ales, lagers and IPA's as well as very happy friends, family and neighbors. His love for the unique keeps him constantly in search of \"new and different\" ingredients and the hope of a perfect combination.\r\n\r\nOne hot July evening, some friends disclosed they were embarking on a new restaurant idea. They asked Chris (my husband) if he would brew the beer specifically for their new endeavor. The ABC frowns on beer sold without the proper licensing and selling from the kitchen counter is not a viable option. Thus a new venture began.\r\n\r\nWhat was once a dream is now a reality and we can now bring our own craft beer to our local Lakewood\/Long Beach community. You'll find us just behind the Long Beach Airport.","website":"http:\/\/www.timelesspints.com\/","established":"2013","isOrganic":"N","images":{"icon":"https:\/\/s3.amazonaws.com\/brewerydbapi\/brewery\/m2lpu3\/upload_v1fZ28-icon.png","medium":"https:\/\/s3.amazonaws.com\/brewerydbapi\/brewery\/m2lpu3\/upload_v1fZ28-medium.png","large":"https:\/\/s3.amazonaws.com\/brewerydbapi\/brewery\/m2lpu3\/upload_v1fZ28-large.png"},"status":"verified","statusDisplay":"Verified","createDate":"2013-08-03 22:49:34","updateDate":"2013-08-04 13:19:27","locations":[{"id":"3wVSu9","name":"Main Brewery","streetAddress":"3671 Industry Avenue","extendedAddress":"C1","locality":"Lakewood","region":"California","postalCode":"90712","phone":"(562) 490-0099","website":"http:\/\/www.timelesspints.com\/","hoursOfOperation":"Thu: 4:00 pm - 8:00 pm\r\nFri: 2:00 pm - 8:00 pm\r\nSat: 12:00 pm - 7:00 pm\r\nSun: 12:00 pm - 5:00 pm","latitude":33.8237257,"longitude":-118.1655833,"isPrimary":"Y","inPlanning":"N","isClosed":"N","openToPublic":"Y","locationType":"nano","locationTypeDisplay":"Nano Brewery","countryIsoCode":"US","yearOpened":"2013","status":"verified","statusDisplay":"Verified","createDate":"2013-08-04 13:19:09","updateDate":"2014-07-23 19:11:34","country":{"isoCode":"US","name":"UNITED STATES","displayName":"United States","isoThree":"USA","numberCode":840,"createDate":"2012-01-03 02:41:33"}}]}],"type":"beer"}],"status":"success"}

But if nothing is returned from the search result I get something just like this:

{"currentPage":1,"status":"success"}

So I need to tell if the above result is returned. My JSON is returned into my javascript in a variable called data.

To determine if the JSON in data contains no results I try this javascript code:

if (data.data.length === undefined || data.data.length === null ) {
    $('#modal1').closeModal();
    Materialize.toast('Rate More Beers to See Statistics', 9000) // 4000 is the duration of the toast
}

I have also just tried:

if (data.data === undefined || data.data === null ) {
    $('#modal1').closeModal();
    Materialize.toast('Rate More Beers to See Statistics', 9000) // 4000 is the duration of the toast
}
2
  • 1
    have you tried "data.data == undefined || data.data.length == 0" ? Commented Aug 27, 2015 at 3:12
  • Couldn't you also do !(data.totalResults > 0)? Commented Aug 27, 2015 at 3:15

3 Answers 3

3

You should do the following to check if the data is undefined.

To check if a variable is undefined, you should use typeof.

To check if variable is null you can simply do !variable in most cases. But when using this syntax be aware that if your variable is equal to 0, then it will be interpreted as false.

if (typeof data.data === 'undefined' || data.data === null ) {
    $('#modal1').closeModal();
    Materialize.toast('Rate More Beers to See Statistics', 9000)
}

typeof returns a string representation of what type of variable variable it is. So in the above example its 'undefined'. So we just do the string comparison.

In your attempt: Note: this is incorrect

var data = {"currentPage":1,"status":"success"}; 
// notice that data.data = 'undefined'

// so when you do the following
if (data.data.length === 'undefined')  
// will resolve to 'undefined'.data.length
// 'undefined' does not have data and will resolve to error
Sign up to request clarification or add additional context in comments.

3 Comments

Awesome, thanks! What did I do wrong, and what is the typeof doing?
The last line should just be undefined.length, not undefined.data.length, because the first data is not undefined.
I know that. I am just explaining Mike what he did wrong in his approach as he asked for explanation in the comment.
2

If data is always going to be in first level of the returned JSON (i.e. in the same level/depth as currentPage), then simply check:

// Assuming variable `j` contains the returned JSON
if ('data' in j) {
  // Some data has been returned
}

2 Comments

Simply use the 'not' operator: if (!'data' in j)
That needs to be !('data' in j).
1

You can simply test whether data.data exists:

if (data.data) {
    // Code that uses data.data
} else {
    $("#modal1").closeModal();
    Materialize.toast('Rate More Beers to See Statistics', 9000);
}

Comments

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.