访问json数组元素

时间:2012-12-05 10:56:14

标签: javascript jquery json

此处的演示演示:http://jsfiddle.net/8Q4Lf/3/

我正在 json 上检索一个数组,并使用此函数将其存储在隐藏的input中:

$.post("http://"+ document.domain + baseUrl + "/tickets/getCategoryDepartmentRelation/",
    function(dat){
        $('#departmentsByCategory_array').val(JSON.stringify(dat));         
});

调用返回此值:

{
    "Investigation Request": [
        "Client server",
        "Interface",
        "Engine"
    ],
    "Configure Planning": [
        "Interface",
        "Engine"
    ],
    "Bug Report": [
        "Client server",
        "Interface",
        "Engine",
        "Database"
    ],
    "Development Request": [
        "Interface",
        "Dev Management",
        "Database",
        "Client server",
        "Engine"
    ],
    "Suggestion Box": [
        "Dev Management"
    ],
    "Post Site Feedback": [
        "Web"
    ]
}

这个数组的json表示形式:

Array
(
    [Investigation Request] => Array
        (
            [0] => Client server
            [1] => Interface
            [2] => Engine
        )

    [Configure Planning] => Array
        (
            [0] => Interface
            [1] => Engine
        )

    [Bug Report] => Array
        (
            [0] => Client server
            [1] => Interface
            [2] => Engine
            [3] => Database
        )

    [Development Request] => Array
        (
            [0] => Interface
            [1] => Dev Management
            [2] => Database
            [3] => Client server
            [4] => Engine
        )

    [Suggestion Box] => Array
        (
            [0] => Dev Management
        )

    [Post Site Feedback] => Array
        (
            [0] => Web
        )

)

这会使input填充此数据:

<input type="hidden" name="demo" value="{&quot;Investigation Request&quot;:[&quot;Client server&quot;,&quot;Interface&quot;,&quot;Engine&quot;],&quot;Configure Planning&quot;:[&quot;Interface&quot;,&quot;Engine&quot;],&quot; Bug Report&quot;:[&quot;Client server&quot;,&quot;Interface&quot;,&quot;Engine&quot;,&quot;Database&quot;],&quot; Development Request&quot;:[&quot;Interface&quot;,&quot;Dev Management&quot;,&quot;Database&quot;,&quot;Client server&quot;,&quot;Engine&quot;],&quot;Suggestion Box&quot;:[&quot;Dev Management&quot;],&quot;Ticket Site Feedback&quot;:[&quot;Web&quot;]}" id="departmentsByCategory_array">

我可以用这个来获得完整的数组:

$('#departmentsByCategory_array').val();

但我正在尝试仅检索一个元素的值,例如“Configure Planning”

如何在Javascript或jQuery中使用这些值? (循环,比较......)

2 个答案:

答案 0 :(得分:2)

我发现了这个问题。您在json表示中返回了一个额外的空格,因此您想要访问" Bug Report" "Bug Report"

alert(data[' Bug Report']);

修改后的小提琴:http://jsfiddle.net/8Q4Lf/2/

密钥" Development Request"也是如此。

alert(data[' Development Request']);

答案 1 :(得分:1)

var data = JSON.parse($('#departmentsByCategory_array').val());
data['Configure Planning']; //returns Configure Planning array