Search code examples
jqueryjsongetjson

Read a json key from jQuery


I'm new to jQuery, I tried searching in this forum but couldn't find a solution.

I have json data in the external file. It looks something like this:

"products": {
  "Product A": {
    "Type 1": {
      "subtype": {
        "*config*": [{"layoutName": "1 x 13", "layoutModules": 13},
                    {"layoutName": "2 x 13", "layoutModules": 13}]
      }
    }
  }
} 

I am trying to display product names (i.e. 'Product A' and 'Product B'). Here is my jQuery code:

  $.getJSON('js/products.json', function(data) {
    for (var i in data.products) {
      output=JSON.stringify(data.products.keys[i]);
    }
    document.getElementById("main").innerHTML=output;
  });

But I am not able to get the required data. I get this error in the browser console:

Uncaught TypeError: Cannot read property 'Product A' of undefined.

Can any one tell me what I doing wrong?


Solution

  • A few things here. First of all, your JSON data structure is malformed. Also, please take a look at this for proper usage of the for.. in loop. Keep in mind also that you probably want to do a string concatenation in your for..in loop.

    Take a look at these codes to see if they do what you want. (I have to convert your Product A and Product B into an array within the JSON object.)

    data = 
    {"products":
        [{"Product A":
             {"Type 1":
                   {"subType":[{"layoutName":"1 x 13","layoutModules":13}]}
             }
        },
        {"Product B":
             {"Type 1":
                   {"subType":[{"layoutName":"2 x 13","layoutModules":13}]}
             }
        }]
    };
    
    var content = "";
    for(property in data)
        for(product in data[property]) 
            content += Object.keys(data[property][product])[0] + ", ";
    
    document.getElementById("content").innerHTML = content;
    <div id="content"></div>