2015-08-27 85 views
2

我有一个我用来抓取结果的API。当它得到的结果我得到这样的背:检查JSON是否没有数组

{"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"} 

但如果不从搜索结果中返回我得到的东西,就像这样:

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

所以我需要告诉我们,如果上述结果返回。我的JSON在一个名为data的变量中返回到我的javascript中。

要确定数据的JSON没有结果我试试这个javascript代码:

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 
} 

我也只是尝试:

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 
} 
+1

你试过“data.data == undefined || data.data.length == 0“? – hallie

+0

难道你不能也''(data.totalResults> 0)'? –

回答

3

你应该做以下检查dataundefined

要检查变量是否为undefined,应该使用typeof

要检查变量是否为null在大多数情况下,您只需执行!variable即可。但是,当使用这种语法时,请注意,如果您的变量等于0,那么它将被解释为false

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

typeof返回它是什么类型的变量变量的字符串表示形式。所以在上面的例子中它的'undefined'。所以我们只是做字符串比较。

在你尝试:注:这是不正确

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 
+0

太棒了,谢谢!我做错了什么,这是什么类型的? – Mike

+0

我会更新 – Subash

+0

感谢您的帮助! – Mike

2

如果data总是将是在返回的JSON(即在同一水平/深度currentPage)的第一级,然后简单地检查:

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

是否存在? – Mike

+0

只需使用'not'运算符:'if(!'data'in j)' – stellarchariot

+3

需要是'!'('data'in j)'。 –

1

你可以简单地测试是否存在data.data

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