【问题标题】:Check if JSON does not have an array in it检查 JSON 中是否没有数组
【发布时间】:2015-11-21 06:49:06
【问题描述】:

我有一个用来获取结果的 API。当它得到结果时,我会得到这样的结果:

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

【问题讨论】:

  • 你试过“data.data == undefined || data.data.length == 0”吗?
  • 你不能也做!(data.totalResults > 0)吗?

标签: javascript json parsing


【解决方案1】:

您应该执行以下操作来检查data 是否为undefined

要检查变量是否为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

【讨论】:

  • 太棒了,谢谢!我做错了什么,typeof 在做什么?
  • 最后一行应该是undefined.length,而不是undefined.data.length,因为第一行data不是未定义的。
  • 我知道。我只是在向迈克解释他在评论中要求解释时做错了什么。
【解决方案2】:

如果data 总是位于返回的 JSON 的第一级(即与currentPage 处于同一级别/深度),则只需检查:

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

【讨论】:

  • 只需使用'not'运算符:if (!'data' in j)
  • 那必须是!('data' in j)
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-24
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    • 2023-04-04
    • 2020-05-07
    相关资源
    最近更新 更多