Posted in jquery
23
6:48 am, May 25, 2021

json load from jquery and loop through the results

this is the same as this post but i have added the object to an external test file.

so rather than already having the object data on the page we have to load it somehow

Note: you can test that the object is clean using this: https://jsonlint.com/ 

Ok so i have moved the object into the file /js/test_object.json which now looks like this:

Test File: https://kruxor.com/js/test_object.json 

JSON

{
    "my_object_1": "value1",
    "my_object_2": "value2",
    "my_object_3": "value3"
}

How do we load this file?

We can use the getJSON from jquery to load it, and then dump it into the console

ok so i added all this and i get a bunch of codes returned. 

Javascript

$(document).ready(function(){
  my_json = $.getJSON("https://kruxor.com/js/test_object.json", function(json) {
      console.log(my_json); // this will show the info it in firebug console
  });
/* ok so now we have my_json as a variable -- loop through it */
  
  for (var key in my_json) {
      if (my_json.hasOwnProperty(key)) {
          console.log(key + " -> " + my_json[key]);
      }
  }  
});

Which returns... 

Console

readyState -> 1
(index):271 getResponseHeader -> function(e){var t;if(h){if(!n){n={};while(t=qt.exec(p))n[t[1].toLowerCase()+" "]=(n[t[1].toLowerCase()+" "]||[]).concat(t[2])}t=n[e.toLowerCase()+" "]}return null==t?null:t.join(", ")}
(index):271 getAllResponseHeaders -> function(){return h?p:null}
(index):271 setRequestHeader -> function(e,t){return null==h&&(e=s[e.toLowerCase()]=s[e.toLowerCase()]||e,a[e]=t),this}
(index):271 overrideMimeType -> function(e){return null==h&&(v.mimeType=e),this}
(index):271 statusCode -> function(e){var t;if(e)if(h)T.always(e[T.status]);else for(t in e)w[t]=[w[t],e[t]];return this}
(index):271 abort -> function(e){var t=e||u;return c&&c.abort(t),l(0,t),this}
(index):271 state -> function(){return i}
(index):271 always -> function(){return s.done(arguments).fail(arguments),this}
(index):271 catch -> function(e){return a.then(null,e)}
(index):271 pipe -> function(){var i=arguments;return S.Deferred(function(r){S.each(o,function(e,t){var n=m(i[t[4]])&&i[t[4]];s[t[1]](function(){var e=n&&n.apply(this,arguments);e&&m(e.promise)?e.promise().progress(r.notify).done(r.resolve).fail(r.reject):r[t[0]+"With"](this,n?[e]:arguments)})}),i=null}).promise()}
(index):271 then -> function(t,n,r){var u=0;function l(i,o,a,s){return function(){var n=this,r=arguments,e=function(){var e,t;if(!(i<u)){if((e=a.apply(n,r))===o.promise())throw new TypeError("Thenable self-resolution");t=e&&("object"==typeof e||"function"==typeof e)&&e.then,m(t)?s?t.call(e,l(u,o,R,s),l(u,o,M,s)):(u++,t.call(e,l(u,o,R,s),l(u,o,M,s),l(u,o,R,o.notifyWith))):(a!==R&&(n=void 0,r=[e]),(s||o.resolveWith)(n,r))}},t=s?e:function(){try{e()}catch(e){S.Deferred.exceptionHook&&S.Deferred.exceptionHook(e,t.stackTrace),u<=i+1&&(a!==M&&(n=void 0,r=[e]),o.rejectWith(n,r))}};i?t():(S.Deferred.getStackHook&&(t.stackTrace=S.Deferred.getStackHook()),C.setTimeout(t))}}return S.Deferred(function(e){o[0][3].add(l(0,e,m(r)?r:R,e.notifyWith)),o[1][3].add(l(0,e,m(t)?t:R)),o[2][3].add(l(0,e,m(n)?n:M))}).promise()}
(index):271 promise -> function(e){return null!=e?S.extend(e,a):a}
(index):271 progress -> function(){return s&&(t&&!i&&(l=s.length-1,u.push(t)),function n(e){S.each(e,function(e,t){m(t)?r.unique&&f.has(t)||s.push(t):t&&t.length&&"string"!==w(t)&&n(t)})}(arguments),t&&!i&&c()),this}
(index):271 done -> function(){return s&&(t&&!i&&(l=s.length-1,u.push(t)),function n(e){S.each(e,function(e,t){m(t)?r.unique&&f.has(t)||s.push(t):t&&t.length&&"string"!==w(t)&&n(t)})}(arguments),t&&!i&&c()),this}
(index):271 fail -> function(){return s&&(t&&!i&&(l=s.length-1,u.push(t)),function n(e){S.each(e,function(e,t){m(t)?r.unique&&f.has(t)||s.push(t):t&&t.length&&"string"!==w(t)&&n(t)})}(arguments),t&&!i&&c()),this}

So thats progress as we are loading the data ok, but where is my actual object gone?

What we are seeing here is all the details that the json is returning, but not the actual data...

So what we want to get access to is the responseJSON object

How do we get access to the responseJSON object?

This bit! ^^^ how do i get access to you?,.. 

Ok after a bit of testing this seems to work: (need to add in a document ready)

Javascript

/* lets try this one using each */
console.log("-----[ trying the $.each function ]-----");
$.getJSON("https://kruxor.com/js/test_object.json", function(result) {
   $.each(result, function(key, value) {
      console.log(key);
      console.log(value);
   });
});

Yay its working!

Next i will do a demo looping through nested objects which is more annoying i think..

Javascript

/*
** the old object kept here for reference
var my_object = {
    "my_object_1": "value1",
    "my_object_2": "value2",
    "my_object_3": "value3"
};
*/
$(document).ready(function(){
  my_json = $.getJSON("https://kruxor.com/js/test_object.json", function(json) {
      console.log(my_json); // this will show the info it in firebug console
  });
  // ok so now we have my_json as a variable -- loop through it
  
  for (var key in my_json) {
      if (my_json.hasOwnProperty(key)) {
          console.log(key + " -> " + my_json[key]);
      }
  }  
});

/*
for (var key in my_object) {
    if (my_object.hasOwnProperty(key)) {
        console.log(key + " -> " + my_object[key]);
    }
}
*/

/* lets try this one using each */
console.log("-----[ trying the $.each function ]-----");
$.getJSON("https://kruxor.com/js/test_object.json", function(result) {
   $.each(result, function(key, value) {
      console.log(key);
      console.log(value);
   });
});

View Statistics
This Week
73
This Month
275
This Year
0

No Items Found.

Add Comment
Type in a Nick Name here
 
Related Search Terms
Search Code
Search Code by entering your search text above.
Welcome

This is my test area for webdev. I keep a collection of code snippits here, mostly for my reference. Also if i find a good site, i usually add it here.

Join me on Substack if you want me to send you a collection of the things i have done or found or read for the week. Or follow me on twitter if you prefer, i dont post much but i probably should!

❤👩‍💻🕹

Random Quote
In this case my anchor this week becomes driving almost 2hrs outside of Atlanta to one of my favorite hard core gyms in the world.. MetroFlex aka The Dungeon. The gym owners turn the heat way up so it becomes a fun sweat box and the gym members just watch from afar and leave me alone. I happily drive myself long distances to find MY ANCHOR. Our anchor allows us to have balance, focus and be as productive as possible. And if you're in the middle of a heavy set and your headphones start to fall off your head, like mine did here.. well.. f*ck the headphones. Let em break and fall. You can always get a new pair, but the iron ain't ever gonna lift itself.
Unknown