验证 JSON 数组长度

Validate JSON array length

我正在尝试编写一个 if 语句来确定 getDept JSON 数组是否包含多个值。如果是,则重定向到另一个页面。通过我的研究,它似乎像 getDept.length > 1 一样简单,但我无法完成这项工作。

我的Javascript代码如下:

$.getJSON("https://apex.oracle.com/pls/apex/mfajertest1/department/"+$x('P2_DEPT_NO').value, function(getDept) 
{
    console.log(getDept);
    if(getDept.length == 0)
        {
                window.alert("No Department with that ID");
        }
    else if(getDept.length > 1)
        {   
                apex.navigation.redirect('f?p=71293:11');
        }
    else
        {
    $x('P2_DEPT_NAME').readOnly = false;
    $x('P2_DEPT_NAME').value=getDept.items[0].dname;
    $x('P2_DEPT_NAME').readOnly = true;
    $x('P2_DEPT_LOC').readOnly = false;
    $x('P2_DEPT_LOC').value=getDept.items[0].loc;
    $x('P2_DEPT_LOC').readOnly = true;
    $x('P2_DEPT_NO').readOnly = true;
  }
});

getDept JSON 数组包含以下信息:

{
    "next": {
        "$ref": "https://apex.oracle.com/pls/apex/mfajertest1/department/%7Bid%7D?page=1"
    },
    "items": [
        {
            "deptno": 10,
            "dname": "accounting",
            "loc": "madison"
        },
        {
            "deptno": 20,
            "dname": "Finance",
            "loc": "Milwaukee"
        },
        {
            "deptno": 30,
            "dname": "IT",
            "loc": "La Crosse"
        },
        {
            "deptno": 40,
            "dname": "Purchasing",
            "loc": "Green Bay"
        },
        {
            "deptno": 10,
            "dname": "Accounting II",
            "loc": "Madison II"
        },
        {
            "deptno": 50,
            "dname": "Sports",
            "loc": "Waukasha"
        }
    ]
}

如果需要,我很乐意提供有关此问题的更多信息。

您的 JSON 响应实际上是一个对象,而不是数组。您要检查的数组是 属性 对象内的一个名为 items 的数组。因此,无论您在哪里使用 getDept,您都应该使用 getDept.items:

$.getJSON("https://apex.oracle.com/pls/apex/mfajertest1/department/"+$x('P2_DEPT_NO').value, function(getDept) 
{
    console.log(getDept.items);
    if(getDept.items.length == 0)
        {
                window.alert("No Department with that ID");
        }
    else if(getDept.items.length > 1)
        {   
                apex.navigation.redirect('f?p=71293:11');
        }
    else
        {
    $x('P2_DEPT_NAME').readOnly = false;
    $x('P2_DEPT_NAME').value=getDept.items[0].dname;
    $x('P2_DEPT_NAME').readOnly = true;
    $x('P2_DEPT_LOC').readOnly = false;
    $x('P2_DEPT_LOC').value=getDept.items[0].loc;
    $x('P2_DEPT_LOC').readOnly = true;
    $x('P2_DEPT_NO').readOnly = true;
  }
});