2012-08-02 40 views
3

我試圖從RESTful服務填充一個電子表格,有時有沒有這樣的屬性,因此我在電子表格中得到一個「未定義」和腳本停止「不確定」和給出錯誤。我不知道如何去處理它,或者跳過「未定義」的部分。如何我會趕上並處理來自解析的JSON對象

下面是JSON

{

"rel": "self", 
"url": "https://www.sciencebase.gov/catalog/items?max=2&s=Search&q=project+ 
2009+WLCI&format=json&fields=title%2Csummary%2Cspatial%2Cfacets", 
"total": 65, 
"nextlink": { 
    "rel": "next", 
    "url": "https://www.sciencebase.gov/catalog/items?max=2&s= 
Search&q=project+2009+WLCI&format=json&fields=title%2Csummary%2 
Cspatial%2Cfacets&offset=2" 
}, 
"items": [ 
    { 
     "link": { 
      "rel": "self", 
      "url": "https://www.sciencebase.gov/catalog/item/ 
      4f4e4ac3e4b07f02db67875f" 
     }, 
     "id": "4f4e4ac3e4b07f02db67875f", 
     "title": "Decision-Making and Evaluation - Social and Economic 
     Evaluation Supporting Adaptive Management for WLCI", 
     "summary": "Provide information on the social and economic environment 
     for the WLCI area and provide context for the biological and physical 
     aspects of this project.", 
     "spatial": { 
      "representationalPoint": [ 
       -108.585, 
       42.141 
      ] 
     }, 
     "facets": [ 
      { 
       "startDate": "2007-10-01 00:00:00", 
       "projectStatus": "Active", 
       "facetName": "Project", 
       "_class": "ProjectFacet", 
       "active": true, 
       "className": "gov.sciencebase.catalog.item.facet.ProjectFacet", 
       "endDate": null, 
       "projectType": "Science", 
       "_embeddedClassName": "gov.sciencebase.catalog.item.facet. 
       ProjectFacet" 
      } 
     ] 
    }, 
    { 
     "link": { 
      "rel": "self", 
      "url": "https://www.sciencebase.gov/catalog/item 
      /4f4e4ac0e4b07f02db676d57" 
     }, 
     "id": "4f4e4ac0e4b07f02db676d57", 
     "title": "Data and Information Management Products for the Wyoming 
     Landscape Conservation Initiative" 
    } 
] 

}

樣本查詢由於第二項後只有一個冠軍而已,我得到「未定義」如果我試圖讓使用循環的項目的摘要或面等。我想過和嘗試使用if語句如

if (parsedResponse.items[i].summary === "undefined") { 
    Do something here; 
} 

但這似乎並不奏效。任何建議,我可以嘗試讚賞。由於

回答

4

一種解決方案是

if (parsedResponse.items[i].summary == undefined) { 
    Do something here; 
} 

if (parsedResponse.items[i].summary == null) { 
    Do something here; 
} 
+0

謝謝兆字節,這有效! – jc72 2012-08-03 21:08:43

+1

當測試null/undefined/etc時,總是使用'==='運算符而不是== ==! – 2016-09-02 21:10:11

0

這應該工作:

if (typeof(parsedResponse.items[i].summary) === "undefined") { 
+0

謝謝goldenparrot,兆字節的回答結束了工作出這一點更好案件。我沒有意識到這種類型,所以這是非常好的知道! – jc72 2012-08-03 21:07:56

+0

工作,作爲一個字符串? – User 2017-08-16 15:25:07

0
function getLastNonBlankColCrow(sheet,columnName, maxi) { 
    var lastNonBlankColCrow = 0; 
    var rangeded = sheet.getRange(columnName+1+":"+columnName+maxi).getValues(); 
    for (var i=0;i<=maxi; i++) 
    { 
     if (rangeded[i] == undefined) 
     { 
     } 
     else 
    { 
     if (rangeded[i][0]!="") 
     { 
     lastNonBlankColCrow = i+1; 
     } 
     } 
    } 
    return lastNonBlankColCrow; 
    }