我如何从解析的json对象中捕获并处理"undefined"

jc7*_*c72 4 google-apps-script

我正在尝试从RESTful服务填充电子表格,有时候没有这样的属性,所以我在电子表格中得到"未定义",脚本停止并发出错误.我不知道如何处理它,或跳过"未定义"部分.

这是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"
    }
]
Run Code Online (Sandbox Code Playgroud)

}

由于第二个项目只有一个标题,之后没有更多,如果我尝试使用循环获取项目的摘要或方面等,我会得到"未定义".我已经想过并尝试使用if语句

if (parsedResponse.items[i].summary === "undefined") {
    Do something here;
}
Run Code Online (Sandbox Code Playgroud)

但这似乎不起作用.我可以尝试任何建议表示赞赏.谢谢

meg*_*024 8

一个解决方案是

if (parsedResponse.items[i].summary == undefined) {
    Do something here;
}
Run Code Online (Sandbox Code Playgroud)

要么

if (parsedResponse.items[i].summary == null) {
    Do something here;
}
Run Code Online (Sandbox Code Playgroud)

  • 在测试 null/undefined/etc 时,始终使用 `===` 运算符而不是 `==`! (2认同)