0

I've searched for the answer to this question, in many places. However, the only thing I can find is how to get the values of all of a certain key in a JSON file. I would like to know if there is a way to get the value of one specific key. I have a JSON file set up like so:

{
"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"
            }
        }    
    }]
}

I would like to know a method using JQuery/Javascript to get, for example, the value of Key1 in Item1(value1).

Zuve
  • 19
  • 3

2 Answers2

0

You can simply do:

Category[0].Subcategory.Item1.key1
Rahul Arora
  • 4,503
  • 1
  • 16
  • 24
0

Like other comments and answers, you can easily get the value for a specific hard-coded key like this:

Category[0].Subcategory.Item1.key1

But if you have dynamic keys, you can do like this:

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];
Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
  • How would I use the console.log from another file. Would it be something like console.log('path/filename.json'.category[0].SubCategory.Item1.Key1); – Zuve Jul 31 '16 at 08:58
  • "How would I use the console.log from another file" - does not work that way. In javascript, you cannot require another file. Although you can load it over XHR request, parse it and then log the contents to the console. – Jerguš Lejko Jul 31 '16 at 09:01