获取JSON值

时间:2013-04-22 16:48:37

标签: javascript json jquery

我需要在我的java脚本中从这个JSON中获取值:

[{
        "selectionName": "Select",
        "subSelections": [{
                "id": 4,
                "subSelectionName": "Select",
                "description": "Deepmala"
            }
        ]
    }, {
        "selectionName": "week14",
        "subSelections": [{
                "id": 7,
                "subSelectionName": "1",
                "description": ""
            }
        ]
    }, {
        "selectionName": "test",
        "subSelections": [{
                "id": 6,
                "subSelectionName": "test",
                "description": ""
            }
        ]
    }, {
        "selectionName": "select",
        "subSelections": [{
                "id": 3,
                "subSelectionName": "sub-select",
                "description": "Created by Prakash"
            }
        ]
    }, {
        "selectionName": "testcreate",
        "subSelections": [{
                "id": 1,
                "subSelectionName": "testcreate",
                "description": ""
            }
        ]
    }, {
        "selectionName": "by htmlwidget",
        "subSelections": [{
                "id": 5,
                "subSelectionName": "by htmlwidget",
                "description": "created by html widget"
            }
        ]
    }
]

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

您可以使用类似JSONSelect的内容来提取某些值。

http://jsonselect.org/

以下是如何使用它的示例:

(见this JSFiddle

$(function(){
/*
Json as easy as SQL ??? RT @lloydhilaiel JSONSelect - CSS-like selectors for JSON - http://jsonselect.org
Testing...
*/
var jsonData = {
    "name": {
        "first": "Lloyd",
        "last": "Hilaiel"
    },
    "favoriteColor": "yellow",
    "languagesSpoken": [
        {
        "language": "Bulgarian",
        "level": 2},
    {
        "language": "English",
        "level": 1},
    {
        "language": "Spanish",
        "level": 7}
    ]
};

var selector = '.name > *'; // xPath CSS like selector

try {

    var resultObj = JSONSelect.match(selector, jsonData);
    console.log(typeof resultObj);
    console.log(resultObj);
    console.log('- - - - -');

    JSONSelect.forEach(selector, jsonData, function(resultObj) {
        console.log(typeof resultObj);
        console.log(resultObj);
        console.log('- - - - -');
        $('body').append('<p>' + $.trim(JSON.stringify(resultObj, null, ' ')) + '</p>');
    });

} catch(e) { console.log(e); }

});

答案 1 :(得分:0)

JSON对象易于处理

var JSON = //Your JSON Object

JSON[0].selectName //returns 'Select'

JSON[0].subSelections[0].id //returns 4

and so on.

任何数组对象都可以视为数组。可以使用密钥返回任何映射对象,如JSON对象的字段名称。