如何获取一个特定JSON密钥的值

时间:2016-07-31 08:48:38

标签: javascript jquery json

我在很多地方都在寻找这个问题的答案。但是,我唯一能找到的是如何获取JSON文件中所有特定键的值。我想知道是否有办法获得一个特定密钥的值。我有一个JSON文件设置如下:

{
"Category": [{
    "Subcategory": {
        "Item1": {
            "key1": "value1",
            "key2": "value2",
            "key3": "value3",
            "key4": "value4",
            "key5": "value5",
            "key6": "value6"
        },
        "Item2": {
            "key1": "value1",
            "key2": "value2",
            "key3": "value3",
            "key4": "value4",
            "key5": "value5",
            "key6": "value6"
            }
        }    
    }]
}

我想知道一个使用JQuery / Javascript获取的方法,例如,Item1(value1)中Key1的值。

2 个答案:

答案 0 :(得分:0)

您可以这样做:

Category[0].Subcategory.Item1.key1

答案 1 :(得分:0)

与其他评论和答案一样,您可以轻松获取特定硬编码密钥的值,如下所示:

Category[0].Subcategory.Item1.key1

但是如果你有动态键,你可以这样做:

var categories = {
    "Category": [{
        "Subcategory": {
            "Item1": {
                "key1": "value1",
                "key2": "value2",
                "key3": "value3",
                "key4": "value4",
                "key5": "value5",
                "key6": "value6"
            },
            "Item2": {
                "key1": "value1",
                "key2": "value2",
                "key3": "value3",
                "key4": "value4",
                "key5": "value5",
                "key6": "value6"
            }
        }
    }]
};

var itemKeyName = "Item1";
var keyName = "key1";

console.log(categories.category[0].Subcategory[itemKeyName][keyName];