0

Let's assume I have a json file like this:

{
  "tools":[
  {
    "category1":[
    {
      "name":"Sample Name",
      "description":"Sample Desc",
      "version":"4.1"
    },
    {
      "name":"Another sample name",
      "description":"Another sample desc",
      "version":"1.0"
    }
    ],
    "category2":[
    {
      "name":"Just sample name",
      "description":"Description here",
      "version":"3.0-beta"
    }
    ]
 }
 ]
}

Now I access the file using the $.getJSON() method and a for-loop in it. The goal is to put every category name (category1, category2) into a <h1>-element, then just display the contents of this category. The problem here is that I don't know the category names as they are dynamically changed from time to time. What I've tried so far:

$.getJSON('tools.json', function(data) {
  var output="";
  for (var i in data.tools) {
    output+="<h1>" + data.tools[i] + "</h1>";
     for (var k in data.tools) {
       output+="data.tools[i][k].name - data.tools[i][k].desc - data.tools[i][k].version";
  }
}

This doesn't work because property name is undefined. So now my question is how do I get the category name and then access all of its content without knowing the name of it?

Thanks in advance.

1 Answer 1

1

Try using Object.keys()

   var categories = Object.keys(data.tools[0]);

    $.each(categories, function(index, category){

        $('body').append('<h1>' + category + '</h1>');

        var items = data.tools[0][category];

        $.each(items, function(i, obj){

            $('body').append(obj.name + '<br>');

        });

    });

Here is a fiddle:

http://jsfiddle.net/mf99setb/

Sign up to request clarification or add additional context in comments.

2 Comments

Works great. My only problem is that I now put every category (including its content) into it's own div. This is no problem, but I can't manage to close the div after every item has been appended. I inserted my </div>-append code at the end of the first each-section, but then the div closes right BEFORE every item gets added. Any ideas?
Figured it out myself. Instead of directly appending each category and item, I save them in an output string and add the </div> at the end of each category. When I then append the whole output string to my body, everything works as it should :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.