json load from jquery and loop through the results
<p>this is the same as <a href="https://kruxor.com/view/code/Ce7VD/loop-through-object-json-javascript/">this post</a> but i have added the object to an external test file.</p>
<p>so rather than already having the object data on the page we have to load it somehow</p>
<p>Note: you can test that the object is clean using this: <a href="https://jsonlint.com/" target="blank" rel="noopener">https://jsonlint.com/</a> </p>
<p>Ok so i have moved the object into the file /js/testobject.json which now looks like this:</p>
<p>Test File: <a href="https://kruxor.com/js/testobject.json">https://kruxor.com/js/testobject.json</a> </p>
<h4>JSON</h4>
<pre><code class="javascript hljs">{<br /> "myobject1": "value1",<br /> "myobject2": "value2",<br /> "myobject3": "value3"<br />}</code></pre>
<p>How do we load this file?</p>
<p>We can use the getJSON from jquery to load it, and then dump it into the console</p>
<p>ok so i added all this and i get a bunch of codes returned. </p>
<h4>Javascript</h4>
<pre><code class="javascript hljs">$(document).ready(function(){<br /> myjson = $.getJSON("https://kruxor.com/js/testobject.json", function(json) {<br /> console.log(myjson); // this will show the info it in firebug console<br /> });<br /> / ok so now we have myjson as a variable -- loop through it /<br /> <br /> for (var key in myjson) {<br /> if (myjson.hasOwnProperty(key)) {<br /> console.log(key + " -> " + myjson[key]);<br /> }<br /> } <br />});<br /></code></pre>
<p>Which returns... </p>
<h4>Console</h4>
<pre><code class="html hljs xml">readyState -> 1<br />(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(", ")}<br />(index):271 getAllResponseHeaders -> function(){return h?p:null}<br />(index):271 setRequestHeader -> function(e,t){return null==h&&(e=s[e.toLowerCase()]=s[e.toLowerCase()]||e,a[e]=t),this}<br />(index):271 overrideMimeType -> function(e){return null==h&&(v.mimeType=e),this}<br />(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}<br />(index):271 abort -> function(e){var t=e||u;return c&&c.abort(t),l(0,t),this}<br />(index):271 state -> function(){return i}<br />(index):271 always -> function(){return s.done(arguments).fail(arguments),this}<br />(index):271 catch -> function(e){return a.then(null,e)}<br />(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()}<br />(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()}<br />(index):271 promise -> function(e){return null!=e?S.extend(e,a):a}<br />(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}<br />(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}<br />(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}</code></pre>
<p>So thats progress as we are loading the data ok, but where is my actual object gone?</p>
<p>What we are seeing here is all the details that the json is returning, but not the actual data...</p>
<p>So what we want to get access to is the responseJSON object</p>
<p>How do we get access to the responseJSON object?</p>
<p><img src="https://i.imgur.com/WKMNPeD.png" /></p>
<p>This bit! ^^^ how do i get access to you?,.. </p>
<p>Ok after a bit of testing this seems to work: (need to add in a document ready)</p>
<h4>Javascript</h4>
<pre><code class="javascript hljs">/ lets try this one using each /<br />console.log("-----[ trying the $.each function ]-----");<br />$.getJSON("https://kruxor.com/js/testobject.json", function(result) {<br /> $.each(result, function(key, value) {<br /> console.log(key);<br /> console.log(value);<br /> });<br />});</code></pre>
<p>Yay its working!</p>
<p><img src="https://i.imgur.com/dIpTQpz.png" /></p>
<p>Next i will do a demo looping through nested objects which is more annoying i think..</p>
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);
});
});