0

I have a json file called example.js The contents of the file look like the below.

    {
        "name":"tom",
        "age":38,
        "gender":"male"
    }

Using the example in the jQuery documentation as a guide

    jQuery.getJSON("example.js", function (data) {
        var items = [];
        jQuery.each(data, function (key, val) {
            items.push("<li id='" + key + "'>" + val + "</li>");

        });
        jQuery("<ul/>", {
            "class": "my-new-list",
            html: items.join("")
        }).appendTo("body");
    });

I can output all the values

    <ul class="my-new-list">
    <li id="name">tom</li>
    <li id="age">38</li>
    <li id="gender">male</li>
    </ul>

However I can't find anywhere where I could just output the persons age for example.

I thought it would have something like age[0] in it but I can't seem to get anything to return when I try this?

ak85
  • 4,154
  • 18
  • 68
  • 113
  • possible duplicate of [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Felix Kling Nov 29 '13 at 00:58

1 Answers1

2

You must use val.age inside the function to pull 38.

$(document).ready(function() {
    $.getJSON("example.js", function(data) {
        $.each(data, function(index, val) {
            $('<li>' + val.age + '</li>').appendTo($('body'));
        });
    });
});
thenewseattle
  • 1,451
  • 1
  • 13
  • 17
  • `data` seems to be an object, not an array of objects. `index` will be each property and `value` will be each value of the property, just like in the OP's code. You should remove the `$.each` call. – Felix Kling Nov 29 '13 at 03:15