Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

accessing anonymous json object

Hi im having a bit of trouble accessing a returned json object, mainly the top level one. Its name in the console returns as Object. Everything I try target comes back undefined like below.

Any help would be greatly appreciated.

//What I try in the console
Object.contents.campaign_data[0].date

{
  "status": {
    "http_code": 200
  },
  "contents": {
    "campaign_data": [
      {
        "key1": "2016-07-03",
        "key2": "something",
        "key3": "2014206",
      },
      {
        "key1": "2016-07-03",
        "key2": "something",
        "key3": "2014206",
      },
      {
        "key1": "2016-07-03",
        "key2": "something",
        "key3": "2014206",
      }
    ]
  }
}

7 Answers

Shane Oliver
Shane Oliver
19,977 Points

before your loop set

var data = data.contents.campaign_data;

this will give you a length of 3 as per your example JSON - then the loop will run and you can debug that

Okay, cheers for the help!

Shane Oliver
Shane Oliver
19,977 Points

OK. Hard to debug code when it's not provided. Is the object properly formatted JSON?

Shane Oliver
Shane Oliver
19,977 Points

Some observations, the getJSON method fails silently if the JSON isn't formatted correctly so you should add a try/catch before executing the code.

Your JSON is invalid, the final value has a comma trailing so it's expecting another string

I'm pretty sure your data.length call in the loop will return undefined

You are should also wait until the JSON is loaded before calling it. use the done/fail methods before executing code

Shane Oliver
Shane Oliver
19,977 Points

You are trying to access an undefined key 'date'. Your keys are key1, key2, key3. Try accessing the values with the correct key

console.log(Object.contents.campaign_data[0].key1);

Sorry should have been more clear, I just changed all the keys/values as they related to client data being pulled through. I just don't seem to be able to access any part of the returned data with what ever I try.

Hopefully below helps/provides insight.

  1. This is were i'm having an issue selecting values from the returned json. Its a bit messy as I stopped and just started working from the console(reason for the commented out code). The log also returns the json properly formatted within the console.

  2. When the call is made I can print the object to the page which returns the properly formatted json above.

$.getJSON(url, function(data) {

                        console.log(JSON.stringify(data, null, 2));

//1. attempt to format into table
//                        var tbl = $("<table/>").attr("id", "client");
//                        $("#responses").append(tbl);
//                        for(var i = 0; i < data.length; i++)
//                        {
//                            var tr = "<tr>";
//                            var td1 = "<td>" + data[i]["date"] + "</td>";
//                            var td2 = "<td>" + data[i]["campaignname"] + "</td>";
//                         var td3 = "<td>" + data[i]["campaigntype"] + "</td></tr>";
//
//                            $("#client").append(tr + td1 + td2 + td3);

//                        }
//2. Prints to page
//                        $('#responses')
////                            .html('<pre id="client"/>')
////                            .find('pre')
////                            .text(JSON.stringify(data, null, 2));
////                            console.log(data);


                    });

If I console just data with out the formatting I get: So I was guessing the top most object is called Object if I'm understanding it correctly.

Object {status: Object, contents: Object}

The invalid formatting is probably my fault when pasting in and changing the values/cutting. I've doubl checked the the returned json and it validates in JSONLINT.

I'll have a look into adding try/catch and you are correct data.length returns undefined.