Join the Stack Overflow Community
Stack Overflow is a community of 6.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I am able to pass an entire JSON object but am unable to index any information from it.

For instance the following code will put the entire JSON string as a single item in an unordered list

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Victoria Traffic</title>
</head>
<body>
    <div id="placeholder"></div>
        <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script>
    $.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent('http://traffic.vicroads.vic.gov.au/maps.json') + '&callback=?', function(data){
        var output = "<ul>";
        output += data.contents;
        output += "</ul>";
        document.getElementById("placeholder").innerHTML = output;
  });
    </script>
</body>
</html>

However the following code will not output anything with the console saying: Cannot read property '0' of undefined.

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Victoria Traffic</title>
</head>
<body>
    <div id="placeholder"></div>
        <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script>
    $.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent('http://traffic.vicroads.vic.gov.au/maps.json') + '&callback=?', function(data){
        var output = "<ul>";
        output += data.contents.incidents[0].id;
        output += "</ul>";
        document.getElementById("placeholder").innerHTML = output;
  });
    </script>
</body>
</html>

What am I doing wrong?

share|improve this question
    
What is data.contents? It evidently doesn't contain a property named incidents. – p.s.w.g Feb 3 '14 at 22:56
1  
Without seeing the JSON data we really can't tell what is going wrong. – Ken Herbert Feb 3 '14 at 22:56
up vote 1 down vote accepted

The response from whateverorigin.org appears to be JSON contained within JSON:

{"contents": "{\"incidents\": ...}"}

While getJSON() will parse the initial response for you, you'll have to parse the inner value yourself:

var contents = $.parseJSON(data.contents);

var output = "<ul>";
output += contents.incidents[0].id;
output += "</ul>";
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.