Posted in jquery
11700
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
491
This Month
1788
This Year
3238

No Items Found.

Add Comment
Type in a Nick Name here
 
Other Items in jquery
wrap an iframe with another div inside another div add a custom event trigger in jquery document ready fancybox inline auto size modal easy jquery load wait function add a toggle with jquery and change the class load json data url with jquery validate email address from string with jquery working function mouse enter mouse leave jquery hover hoverout simulate a click on an element with jquery append a #link to the end of all href urls on a target scroll down the page using a button click check if a ul contains a ul li jquery check if a sub element exists jquery toggle menu testing json load from jquery and loop through the results json jquery ajax request add click event to multiple link items and load the link content into a target div ajax add click event to multiple link items Uncaught TypeError: $(...).slideToggle is not a function jquery page search [testing] animate and zoom six elements on a timer [addClass, removeClass, setTimeout] add a jquery date picker to your text box replicating the bootstrap dropdown toggle in jquery using jquery appear for checking if an element is visible on screen fix for Uncaught TypeError: e.indexOf is not a function add a class or remove it based on window scroll location find and replace hrefs in existing page links using jquery get the href value using jquery jquery document ready with foundation init as well jquery add a click function if the window size is greater than target_width jquery enable and disable attribute jquery click function Change link target with JQuery document ready wordpress jquery
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 here, mostly for my reference. Also if i find a good link, i usually add it here and then forget about it. more...

Subscribe to weekly updates about things i have added to the site or thought interesting during the last week.

You could also follow me on twitter or not... does anyone even use twitter anymore?

If you found something useful or like my work, you can buy me a coffee here. Mmm Coffee. ☕

❤️👩‍💻🎮

🪦 2000 - 16 Oct 2022 - Boots
Random Quote


Bajo
Random CSS Property

scroll-margin-block-end

The scroll-margin-block-end property defines the margin of the scroll snap area at the end of the block dimension that is used for snapping this box to the snapport. The scroll snap area is determined by taking the transformed border box, finding its rectangular bounding box (axis-aligned in the scroll container's coordinate space), then adding the specified outsets.
scroll-margin-block-end css reference