0

Recently posted about looking through some json output from an API and got pointed to $getJSON and for loop issue

But im still really struggling and nothing I do works.

I have the following output from an API call :

    {
  "about": {
    "name": "API",
    "version": "2018.1.25.1",
    "method": "get"
  },
  "sessions": {
    "0": {
      "sessionid": "c6fac08ad020cd10c377b77b81aac2ed19c08111",
      "id": "121667",
      "geolat": "51.9125118",
      "geolon": "-2.1210269"
    },
    "1": {
      "sessionid": "4f3da85c4905ee8c2a57ac48a22184b93fc2f680",
      "id": "122589",
      "chatstarted": "2018-02-24 23:41:51",
      "geolat": "51.9125118",
      "geolon": "-2.1210269"
    }
  },
  "rescode": "200",
  "executed": "nokeyfound-",
  "queries": "5"
}

I just cant get it to loop through the "sessions" part of the Json.

The below "sort of works" but doesnt work at all, no errors, no output when loading it using $.getJSON (rather than just manually creating the object)

$.getJSON('https://api.php', function (Json) {
    for (i in Json.sessions) {
        alert(Json.sessions[i].id);
}

Surely it can't be that hard to just loop through only part of the data returned (the sessions) part.

What on earth am I doing wrong with this loop?

I just want to output sessionid on both rows. Seems impossible and been at this now for 9 hours straight no luck,

There has to be a way to just look at the sessions part and loop through the bits of that? surely? (0, 1 ,2 ,3 etc.. )

P.S I'm new to Javascript and JSON in particular and this is driving me insane.

Graham Smart
  • 43
  • 1
  • 12
  • 1
    Have you checked what was actually send, does the response contain `sessions` object? What you currently are doing, is exactly "_just look at the sessions part and loop through the bits of that_". – Teemu Mar 12 '18 at 17:49
  • quick tip: try checking data with console.log() rather than an alert() -- console is a lot friendlier for displaying (use 'web developer tools' to see the console) – Doug Mar 12 '18 at 17:52
  • Hi, yes, The above is what is stored in Json (returned from the getJSON call) – Graham Smart Mar 12 '18 at 17:53
  • Hi, tried console.log and it just shows undefined. – Graham Smart Mar 12 '18 at 17:54
  • It looks like your code would work [as it is](https://jsfiddle.net/nzkLoxya/1/) ..? (`sessions['1']` doesn't contain `id` property, hence `undefined` is logged for that.) – Teemu Mar 12 '18 at 17:58
  • apologies, bad sanitisation on my behalf, it states id. – Graham Smart Mar 12 '18 at 18:05
  • Yes, I guessed that, but the point of my comment above was, that your code works as it is, as you can see on the fiddle. It has to be something in the data itself, either it doesn't have `id`s at all, or the object was send as empty/without `sessions` property, or the request fails at the server-side when the callback won't ever be executed. – Teemu Mar 12 '18 at 18:15
  • @Teemu OP has missing `}` in the success function. Your Fiddle doesn't. – Scott Marcus Mar 12 '18 at 18:16
  • @ScottMarcus I'd still trust OP when they're saying "_no errors_" ... Should I = ). – Teemu Mar 12 '18 at 18:17
  • @Teemu He just indicated to me in the comments of my answer that that was, in fact, an issue in his code. – Scott Marcus Mar 12 '18 at 18:18
  • @ScottMarcus The last comment is still "_nada_" ... – Teemu Mar 12 '18 at 18:20

1 Answers1

0

Your result is not valid JSON because of a trailing , here:

"method": "get",

Always verify that the results you get back from a JSON request is valid before doing anything else.

Next, your syntax in the success handler is incorrect. You are missing a closing } for the for loop:

$.getJSON('https://api.php', function (Json) {
    for (i in Json.sessions) {
        alert(Json.sessions[i].id);
    } // <-- You don't have this.
}

But, if we correct those things, then here's how we can iterate the results (keeping in mind that sessions is a key in the main object, but contains another object as its data:

var result =     `{
  "about": {
    "name": "API",
    "version": "2018.1.25.1",
    "method": "get"
  },
  "sessions": {
    "0": {
      "sessionid": "c6fac08ad020cd10c377b77b81aac2ed19c08111",
      "id": "121667",
      "geolat": "51.9125118",
      "geolon": "-2.1210269"
    },
    "1": {
      "sessionid": "4f3da85c4905ee8c2a57ac48a22184b93fc2f680",
      "cid": "122589",
      "chatstarted": "2018-02-24 23:41:51",
      "geolat": "51.9125118",
      "geolon": "-2.1210269"
    }
  },
  "rescode": "200",
  "executed": "nokeyfound-",
  "queries": "5"
}`;

resultObj = JSON.parse(result);

// Loop over the top-level object
for(var key in resultObj){
  // Check the object key for the one we care about
  if(key === "sessions"){
    // Loop over the object stored in that key
    for(var subKey in resultObj[key]){
      // Access the sub-keys with an extra index:
      console.log(resultObj[key][subKey]);
    }
  }
}

Or, to go directly to the sessions object:

var result =     `{
  "about": {
    "name": "API",
    "version": "2018.1.25.1",
    "method": "get"
  },
  "sessions": {
    "0": {
      "sessionid": "c6fac08ad020cd10c377b77b81aac2ed19c08111",
      "id": "121667",
      "geolat": "51.9125118",
      "geolon": "-2.1210269"
    },
    "1": {
      "sessionid": "4f3da85c4905ee8c2a57ac48a22184b93fc2f680",
      "cid": "122589",
      "chatstarted": "2018-02-24 23:41:51",
      "geolat": "51.9125118",
      "geolon": "-2.1210269"
    }
  },
  "rescode": "200",
  "executed": "nokeyfound-",
  "queries": "5"
}`;

resultObj = JSON.parse(result);

// Loop over the top-level object
for(var key in resultObj.sessions){
    // Loop over the object stored in that key
    for(var subKey in resultObj.sessions[key]){
      // Access the sub-keys with an extra index:
      console.log(subKey + " = " + resultObj.sessions[key][subKey]);
    }
}
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • Maybe it is just a shortened version of the original JSON in the post? A trailing comma would fire an internal error in jQuery, OP says "no errors". – Teemu Mar 12 '18 at 17:58
  • @Teemu Nonetheless, the rest of my answer answers how to loop the object. – Scott Marcus Mar 12 '18 at 17:59
  • Ah yes, it is shortened, the real one doesn't have a trailing , I have just tried your way and still no output. grr I changed var key in Json (json being the name used after the .getJSON ( function )Json) – Graham Smart Mar 12 '18 at 18:01
  • @GrahamSmart And, you know you have another error with your success handler (missing `}`), right? – Scott Marcus Mar 12 '18 at 18:11
  • THANKS, im getting closer.. So. resultObj .. I see you JSON.parse it.. Does that need to happen if i .getJson? – Graham Smart Mar 12 '18 at 18:14
  • @GrahamSmart No, you don't need `JSON.parse()`. I was only trying to mimic what you were getting back as close as I could. – Scott Marcus Mar 12 '18 at 18:14
  • ok, so in theory, $.getJSON('https://api.php', function (resultObj) { } Should work? – Graham Smart Mar 12 '18 at 18:16
  • @GrahamSmart Everything after my `resultObj = JSON.parse(result);` makes my code identical to what you would have and would work just as mine does. – Scott Marcus Mar 12 '18 at 18:17
  • ok thanks, weirdly, it doesnt show anything. no errors, nada. AT least i have something to go on now. Thanks!! – Graham Smart Mar 12 '18 at 18:19
  • @GrahamSmart Again, I would add `console.log(Json)` as the first line of code in your success callbck to ensure you are getting data and that your call is being made in the first place. – Scott Marcus Mar 12 '18 at 18:20
  • 1
    @GrahamSmart Alternatively, you can look at the `Network` tab of your developer's tools to ensure the request is getting made and a response is coming back. – Scott Marcus Mar 12 '18 at 18:21
  • Ah, if I echo the getJson into the console it actually doesnt show the "sessions" part. Its like Jquery is ignoring it... what the. YET! the network tab shows all the data is actually returned. Its as is jquery doesnt like it being nested. – Graham Smart Mar 12 '18 at 18:22
  • @GrahamSmart That is always the first thing to do in any AJAX call (just to make sure you don't waste time later) -- check the result and make sure it is there, it's valid and what you expect. – Scott Marcus Mar 12 '18 at 18:23
  • @GrahamSmart Copy that echo'd data into https://jsonlint.com to make sure it's valid. – Scott Marcus Mar 12 '18 at 18:24
  • Yep, 100% valid json. Yet jquery for some reason decides to omit the "sessions" section and skips to the next bit. Wow. trust me to have this issue – Graham Smart Mar 12 '18 at 18:28
  • @GrahamSmart Are you in control of the JSON that is returned? Just for kicks could you rename `sessions` to `TEST` and see if it comes all the way through? – Scott Marcus Mar 12 '18 at 18:31
  • hi, yeah i am. Just tried and nothing. Its like it doesnt like nested information and drops the whole section. – Graham Smart Mar 12 '18 at 18:34
  • `getJson` uses `$.parseJSON` method to parse the send data. It looks like it [would work](https://jsfiddle.net/nzkLoxya/7/) too ..? – Teemu Mar 12 '18 at 18:34
  • Interestingly if i just use $get )rather than json) it still ignores it. Wow, something weird going on here. At least I know the above code works!! So thanks for that! Once I get this odd data transfer fixed it should work! So i am very grateful for your help! – Graham Smart Mar 12 '18 at 18:36
  • @GrahamSmart And, what if you were to (just for fun), change `seesions` to return a static primitive value (like `"HELLO"`, rather than a nested object? Just to see (or to rule out) the whole nested data being dropped theory (because that is not what happens with JSON structures). – Scott Marcus Mar 12 '18 at 18:38
  • Yep. If i added a new one called moo it works fine.. "rescode": "200", "moo": "hello", "executed": "nokeyfound-", "queries": "15" – Graham Smart Mar 12 '18 at 18:40
  • Looks like ive tracked it down to some browser session issues. Removed a bunch of checks and it seems to show now. Thanks again!! My headache is going away now. – Graham Smart Mar 12 '18 at 18:56
  • @GrahamSmart That's great. It would be good if you would just post an update to what the exact issue was for others who may run into the same issue. – Scott Marcus Mar 12 '18 at 19:09
  • The exact issue was my stupidity unfortunately. I had a session running on one test machine and not on another and getting differing results. Your code above as an answer to my question works perfectly if I wasn't in the middle if it all :) – Graham Smart Mar 12 '18 at 19:16