473,796 Members | 2,460 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Iterate through JSON property list

RMWChaos
137 New Member
Any JSON experts out there? I'd like to know if it is possible, and if so how, to iterate through a JSON property list so that each iteration selects the next value for each object. Here is an example list:

Expand|Select|Wrap|Line Numbers
  1. function myFunction()
  2. {
  3.     createDOM({
  4.     'id'      :   ["formname", "inputname", "submitbutton"],
  5.     'dom'     :   ["form", "input", "input"],
  6.     'parent'  :   "content",
  7.     'form'    :   [null, "formname", "formname"],
  8.     'action'  :   [URI, null, null],
  9.     'method'  :   ["post", null, null],
  10.     'type'    :   [null, null, "submit"],
  11.     'size'    :   [null, 6, null],
  12.     'value'   :   [null, null, "Submit"],
  13.     )};
  14. };
  15.  
Now what I want to do is iterate through this list 3 times, in each case selecting the next value for each object. So through each iteration, it will go through all the objects (id, dom, parent, etc.). On the first run it will select the first set of values for each object (formname, form, content, null, URI, etc.). On the second run, it will select the second set (inputname, input, content, formlogin, etc.) and so on. In the case of the 'parent' object, it will select 'content' on each run.

I know one way to do this, but it involves creating an array for each object's value list, like so:

Expand|Select|Wrap|Line Numbers
  1. function myFunction()
  2. {
  3. var A = new Array ("formname", "inputname", "submitbutton");
  4. var B = new Array ("form", "input", "input");
  5. var C = new Array(null, "formname", "formname");
  6. var x = 0;
  7. var D = A.length + x;
  8. var E = B.length + x;
  9. var F = C.length + x;
  10.  
  11. for (x <= 3; x >= 0; x++)
  12.     {
  13.     createDOM({
  14.     'id'      :   D,
  15.     'dom'     :   E,
  16.     'parent'  :   F,
  17.     )};
  18. };
  19.  
That would result in a long list of arrays and "array.leng th + x" vars. So I am hoping there is an easier way by working with the first example.

Thanks!
Nov 13 '07
25 25453
gits
5,390 Recognized Expert Moderator Expert
Huh? :-\
If I understand you correctly, you mean that if the attribute does not exist, then I can modify the element on the fly, but if the attribute is null or 'undefined' I couldn't? Is that what you are saying?

I'm pretty sure that I can do "elemId.attribN ame = newValue" regardless of whether the attribute already exists or not, or whether it is set to null or 'undefined'. That's how my mouseHover() function works.
no ... it was an example for the input-box readonly-attrib locks the input and removing the attrib makes it editable (inputable) again. and with elemId.attribNa me = newValue you mix up two different things. you setting the javascript-property of an element with setAttribute('a ttribName', 'newValue'); you set the dom-attribute. setting the js-property effects the element directly ... and overwrites the setted attributes ... so sometimes it could be difficult to debug such things that mixes the two ways and it would be good practice to use only one-way the attibute OR the property way ...

kind regards
Nov 15 '07 #11
RMWChaos
137 New Member
...and with elemId.attribNa me = newValue you mix up two different things. you setting the javascript-property of an element with setAttribute('a ttribName', 'newValue'); you set the dom-attribute. setting the js-property effects the element directly ... and overwrites the setted attributes ... so sometimes it could be difficult to debug such things that mixes the two ways and it would be good practice to use only one-way the attibute OR the property way ...
Oh, right, you told me not to mix up the two variations before. So to clarify:

Expand|Select|Wrap|Line Numbers
  1. // This sets the javascript property
  2. element[attribute] = value;
  3. // or
  4. element.attribute = value;
  5.  
  6. // And this sets the DOM-node attribute
  7. element.setAttribute(attribute, "value");
  8.  
Have I got it right? Can you tell me is there any advantage to using one method over the other? I realize that they do not operate in exactly the same way; so perhaps the answer is, "It depends on what you want to do." I don't know enough about the differences between the two methods to understand if one method suites my needs over the other. That will be my research project for today.
Nov 15 '07 #12
gits
5,390 Recognized Expert Moderator Expert
hmmm ... you gave the answer already :) ... personally i would always use the attribute way since i consider it a dom operation and i would like to use dom-methods for this purpose ... but in IE you cannot set the onclick handler with set attribute for example ... but i wouldnt do that anyway ... since i would use a generalized event-handling with addEventListene r() and attachEvent() ... so as you can see one should make a choice ... and i think sometimes, when using some js-constructs (or not using them) you cannot avoid the mixing of the two ways ... but as i said ... in huge projects it could lead to strange things and then it could be difficult to debug by team-members that didn't know all the code ...

a solution for the mix-up-thing could be to create a util-method ... that centralizes the handling ... so that would be a typical framework-candidate :)

kind regards
Nov 15 '07 #13
RMWChaos
137 New Member
... but i wouldnt do that anyway ... since i would use a generalized event-handling with addEventListene r() and attachEvent() ...
Ok, I use addEvent() as well, but I have no idea how you mean to use it in this case. I'll post my code below.

...a solution for the mix-up-thing could be to create a util-method ... that centralizes the handling ... so that would be a typical framework-candidate.
Wha-? Now you're just showing off. ;-D I have no idea what a util-method is.

Here's my addEvent() code. How would I use this as you suggested?
Expand|Select|Wrap|Line Numbers
  1. if(Array.prototype.push == null)
  2.  
  3.     {
  4.  
  5.     Array.prototype.push = function()
  6.  
  7.         {
  8.  
  9.         for(var i = 0; i < arguments.length; i++)
  10.  
  11.             {
  12.  
  13.             this[this.length] = arguments[i];
  14.  
  15.             };
  16.  
  17.         return this.length;
  18.  
  19.         };
  20.  
  21.     };
  22.  
  23. function addEvent(obj, type, fn)
  24.  
  25.     {
  26.  
  27.     if (obj.addEventListener) // FireFox, NN, Mozilla, etc.
  28.  
  29.         {
  30.  
  31.         obj.addEventListener(type, fn, false);
  32.  
  33.         // bugzilla bug #241518
  34.  
  35.         EventCache.add(obj, type, fn);
  36.  
  37.         }
  38.  
  39.     else if (obj.attachEvent) // MSIE
  40.  
  41.         {
  42.  
  43.         var func = function()
  44.  
  45.             {
  46.  
  47.             fn.apply(window.event.srcElement);
  48.  
  49.             };
  50.  
  51.         obj.attachEvent("on" + type, func);
  52.  
  53.         EventCache.add(obj, type, func);
  54.  
  55.         }
  56.  
  57.     else if (typeof obj['on' + type] != 'function') // old
  58.  
  59.         {
  60.  
  61.         obj['on' + type] = fn;
  62.  
  63.         }
  64.  
  65.     else // really old
  66.  
  67.         {
  68.  
  69.         var oldonload = obj['on' + type];
  70.  
  71.         obj['on' + type] = function()
  72.  
  73.             {
  74.  
  75.             oldonload();
  76.  
  77.             fn();
  78.  
  79.             };
  80.  
  81.         };
  82.  
  83.     };
  84.  
  85.  
  86. function removeEvent(obj, type, fn)
  87.  
  88.     {
  89.  
  90.     EventCache.remove(obj, type, fn);
  91.  
  92.     };
  93.  
  94.  
  95. var EventCache = function()
  96.  
  97.     {
  98.  
  99.     var listEvents = [];
  100.  
  101.     return {
  102.  
  103.         listEvents : listEvents,
  104.  
  105.         add : function(node, sEventName, fHandler)
  106.  
  107.             {
  108.  
  109.             listEvents.push(arguments);
  110.  
  111.             },
  112.  
  113.         remove : function(node, sEventName, fHandler)
  114.  
  115.             {
  116.  
  117.             var i, item;
  118.  
  119.             for(i = listEvents.length - 1; i >= 0; i = i - 1)
  120.  
  121.                 {
  122.  
  123.                 if(node == listEvents[i][0] && sEventName == listEvents[i][1] && fHandler == listEvents[i][2])
  124.  
  125.                     {
  126.  
  127.                     item = listEvents[i];
  128.  
  129.                     if(item[0].removeEventListener)
  130.  
  131.                         {
  132.  
  133.                         item[0].removeEventListener(item[1], item[2], item[3]);
  134.  
  135.                         };
  136.  
  137.                     if(item[1].substring(0, 2) != "on")
  138.  
  139.                         {
  140.  
  141.                         item[1] = "on" + item[1];
  142.  
  143.                         };
  144.  
  145.                     if(item[0].detachEvent)
  146.  
  147.                         {
  148.  
  149.                         item[0].detachEvent(item[1], item[0][sEventName+fHandler]);
  150.  
  151.                         };
  152.  
  153.                     item[0][item[1]] = null;
  154.  
  155.                     };
  156.  
  157.                 };
  158.  
  159.             },
  160.  
  161.         flush : function()
  162.  
  163.             {
  164.  
  165.             var i, item;
  166.  
  167.             for(i = listEvents.length - 1; i >= 0; i = i - 1)
  168.  
  169.                 {
  170.  
  171.                 item = listEvents[i];
  172.  
  173.                 if(item[0].removeEventListener)
  174.  
  175.                     {
  176.  
  177.                     item[0].removeEventListener(item[1], item[2], item[3]);
  178.  
  179.                     };
  180.  
  181.                 if(item[1].substring(0, 2) != "on")
  182.  
  183.                     {
  184.  
  185.                     item[1] = "on" + item[1];
  186.  
  187.                     };
  188.  
  189.                 if(item[0].detachEvent)
  190.  
  191.                     {
  192.  
  193.                     item[0].detachEvent(item[1], item[2]);
  194.  
  195.                     };
  196.  
  197.                 item[0][item[1]] = null;
  198.  
  199.                 };
  200.  
  201.             }
  202.  
  203.         };
  204.  
  205.     }();
  206.  
  207.  
  208. /* *******************************************
  209.    **           Initialize Events           **
  210.    ******************************************* */
  211.  
  212. function loadScripts()
  213.  
  214.     {
  215.  
  216.     loadScript('../scripts/DOMLoader.js');
  217.  
  218.     loadScript('../scripts/XHRLoader.js');
  219.  
  220.     loadScript('../scripts/FADELoader.js');
  221.  
  222.     loadScript('../scripts/LOGINLoader.js');
  223.  
  224.     loadScript('../scripts/NAVLoader.js');
  225.  
  226.     };
  227.  
  228. addEvent(window, 'load', loadScripts);
  229.  
  230. addEvent(window, 'reset', loadScripts);
  231.  
  232. addEvent(window, 'unload', EventCache.flush);
  233.  
  234. addEvent(window, 'reset', EventCache.flush);
  235.  
Nov 15 '07 #14
gits
5,390 Recognized Expert Moderator Expert
hi ...

i'm sorry for confusing you ... was a little bit late yesterday :) ... let me explain it a little bit more clearly:

when you have to mix the property and attribute way for some reason ... you should centralize the handling of setting the value with a custom method like the following (and i use the onclick only for demonstration now ... you use the better attachEvent() - handling already ... but if you need to set a property because the attibute doesn't work as you expect then you may replace it or extend the exception list ... ok?) its only a general discussion ... and may be it is of some help for you or others that read the thread:

Expand|Select|Wrap|Line Numbers
  1. /** 
  2.  * the util-method is a simple method that encapsulates the
  3.  * setAttribute() and property-setting - i simply call it set_node_attrib 
  4.  * @param docroot the document
  5.  * @param id node-id
  6.  * @param attr_state true when we wnat to set the value
  7.  * explicitly, false when we want to remove it
  8.  * @param attr the attribute-name
  9.  * @param the value to set 
  10.  */
  11. function set_node_attr(docroot, id, attr_state, attr, value) {
  12.     var node = docroot.getElementById(id);
  13.     var exceptions = { onclick: 1 };
  14.  
  15.     if (attr in exceptions) {
  16.         _set_node_prop(node, attr, value);
  17.     } else  if (attr_state) {
  18.         node.setAttribute(attr, value);
  19.     } else {
  20.         node.removeAttribute(attr);
  21.     }
  22. }
  23.  
  24. /**
  25.  * @private
  26.  */
  27. function _set_node_prop(node, attr, value) {
  28.     node[attr] = value;
  29. }
and now we should always use the set_node_attr() ; method and we always know where the attribs and properties are controlled ... ok?

kind regards
Nov 16 '07 #15
RMWChaos
137 New Member
Ok, took me a few times reading through your code to fully understand it, but I get it now. So basically, you create an exception list for attributes that are problematic or don't add the same in all browsers. If the attribute is in the exception list, it calls _set_node_prop( ), which uses the javascript node[attr] = value method. If the attrib is not in the exception list, it uses the DOM node.setAttribu te(attr, value) method. Makes sense now.

But why a separate function for exceptions rather than this:
Expand|Select|Wrap|Line Numbers
  1. function set_node_attr(docroot, id, attr_state, attr, value)
  2.     {
  3.     var node = docroot.getElementById(id);
  4.     var exceptions =
  5.         {
  6.         onclick: 1
  7.         };
  8.  
  9.     if (attr in exceptions)
  10.         {
  11.         node[attr] = value;
  12.         }
  13.     else  if (attr_state)
  14.         {
  15.         node.setAttribute(attr, value);
  16.         }
  17.     else
  18.         {
  19.         node.removeAttribute(attr);
  20.         };
  21.     };
  22.  
And how would you remove a attr in the exceptions list? Set value to null?

As for using attachEvent(), I think your example here helped me understand better the addEvent() code I posted (obviously, I didn't write it). I could, for instance, do this:
Expand|Select|Wrap|Line Numbers
  1. addEvent(document.getElementById('image"), "click", someFunction);
  2.  
Nov 16 '07 #16
gits
5,390 Recognized Expert Moderator Expert
hi ...

yes ... that is what i thought :) ... two things:

first: i used a seperate function because it could be that we might have to use a much more complex handling of some properties ... so that the code would be more modular and we could handle the changes a bit better, or we later could have the need to call the property-setter seperatly from another function ... so i always prefer to use a seperate function for a seperate task ...

second: to remove a property from the exeption list we have to remove it ... a better way in huge projects would be to use a constant for the list that is defined in a seperate js-file ... so that we may find that very easy and could adapt the list ... setting the value to 0 wouldn't help, since we actually check with the in operator and that simply checks for the existence in the list ...

kind reagards
Nov 18 '07 #17
RMWChaos
137 New Member
Why this in your code?

/**
* @private
*/
Nov 23 '07 #18
RMWChaos
137 New Member
gits,

This is the code I ended up going with in my createDOM() function to address problems adding certain attributes in different browsers:

Expand|Select|Wrap|Line Numbers
  1. for (index in attrib)
  2.      {
  3.      var exceptions = ({
  4.           'onclick'     :   1,
  5.           'onmouseover' :   1,
  6.           'onmouseout'  :   1
  7.           });
  8.      if (index in exceptions)
  9.           {
  10.           createElem[index] = attrib[index];
  11.           }
  12.      else
  13.           {
  14.           createElem.setAttribute(index, attrib[index]);
  15.           };
  16.      };
  17.  
I understand why you suggested making the exception code a seperate function, but for my purposes, this will work fine.

I do have one other question, however. You have the exceptions in a JSON list, so I copied what you did, but is that necessary? Why not just:

Expand|Select|Wrap|Line Numbers
  1. var exceptions = new Array ("onclick", "onmouseover", "onmouseout");
  2.  
There is no data to hold here; so I guess I am missing the point of a JSON property list.

Thanks!
Nov 23 '07 #19
gits
5,390 Recognized Expert Moderator Expert
Why this in your code?

/**
* @private
*/
that's for marking, that you shouldn't use that method seperatly ... only set_node_attr() ; should be used in the code. the reason for that is, that you later on simply may change the functions without changing the code in different places, and so centralizes the attrib/property setting ion one place ...

kind regards
Nov 23 '07 #20

Sign in to post your reply or Sign up for a free account.

Similar topics

2
5239
by: Jim Heavey | last post by:
I want to write a routine which will list all of the propetries and all property names for a particular object, say a DataColumn. I there a way for me to do this without manually looking up each property name and the property value? Thanks in advance for your assistance!!!!!!!!!!!
7
1698
by: Raymond Lewallen | last post by:
Want to know if/how to get a list of properties that are available in a class and store the properties names in an arraylist. TIA, Raymond Lewallen
0
1062
by: zacks | last post by:
I have a class property that is a List of another class. I would like to add an instance to this property via the Type.InvokeMethod method. But when I try invoke the method with a bing flag of SetProperty I get a Missing Method exception. Is it possible to add an instance to a property List via InvokeMethod?
3
16530
by: Steve | last post by:
Hello- I have numerous variables called varNameX (where X is equal to a number from 0 to a known number "n"). Using VB.NET, I would like to iterate through all of these variables to run comparisons. Example:
15
7731
RMWChaos
by: RMWChaos | last post by:
As usual, an overly-long, overly-explanatory post. Better too much info than too little, right? A couple weeks ago, I asked for some assistance iterating through a JSON property list so that my code would either select the next value in the member list or the single value. The original post can be found here. This is the code gits helped me write: for (var i = 0; i < attribList.id.length; i++) { var attrib = {};
4
2823
RMWChaos
by: RMWChaos | last post by:
The next episode in the continuing saga of trying to develop a modular, automated DOM create and remove script asks the question, "Where should I put this code?" Alright, here's the story: with a great deal of help from gits, I've developed a DOM creation and deletion script, which can be used in multiple applications. You simply feed the script a JSON list of any size, and the script will create multiple DOM elements with as many attributes...
3
3828
by: Bitslong | last post by:
I have the following JSON obj/code: var json_logs = { "countries": , "US":{"num_calls":"555","time":"432"}, "AU":{"num_calls":"212","time":"233"} } var call = json_logs.evalJSON();
6
1467
by: Academia | last post by:
VS2008 The help for Form lists ContextMenu as a property but it does not appear in the properties for my form. Is there something I must do to make it appear there. Thanks
3
2349
by: Tyro | last post by:
I have built a database that is updated daily with new items. Each new item needs to be given to someone on our team to work on. I would like to automatically assign the new items to the team members identified on a list and iterate through the list so that the work is distributed evenly. Thanks for any help!
0
9683
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9529
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10231
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10176
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10013
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6792
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5576
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3733
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2927
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.