Xtian
Xtian

Reputation: 3587

Json reponse unexpectedly returns [object Object]

All I want is a simple output of a JSON file. Right now it is giving me back [object Object].

What am I doing wrong?

<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $.getJSON("team.json",function(result){
      $.each(result, function(i, field){
        $("div").append(field + " ");
      });
    });
  });
});
</script>
</head>
<body>

<button>Get JSON data</button>
<div></div>

Upvotes: 0

Views: 812

Answers (2)

BalusC
BalusC

Reputation: 1108812

The result is apparently an object {}, not an array [] as your code seems to expect. An object has several properties which you need to access individually.

Probably the JSON object in turn contains an array property which you need to access instead. E.g.

{
    teams: [
        // ...
    ]
}

which should then be accessed as follows:

$.each(result.teams, function(i, field) {
    // ...
}

Upvotes: 3

ezmilhouse
ezmilhouse

Reputation: 9131

try

$(field + " ").appendTo("div");

Upvotes: 0

Related Questions