473,785 Members | 2,325 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 #1
25 25451
gits
5,390 Recognized Expert Moderator Expert
hi ...

i hope i don't misunderstand your question ... have a look at the following example:

Expand|Select|Wrap|Line Numbers
  1. var data = {
  2.     'id'      :   ["formname", "inputname", "submitbutton"],
  3.     'dom'     :   ["form", "input", "input"],
  4.     'parent'  :   "content",
  5.     'form'    :   [null, "formname", "formname"],
  6.     'action'  :   ['URI', null, null],
  7.     'method'  :   ["post", null, null],
  8.     'type'    :   [null, null, "submit"],
  9.     'size'    :   [null, 6, null],
  10.     'value'   :   [null, null, "Submit"]
  11. };
  12.  
  13. for (var i = 0; i < 3; i++) {
  14.     // array for demonstrating the selection
  15.     var arr = [];
  16.  
  17.     for (var j in data) {
  18.         var prop = data[j];
  19.  
  20.         // the 'parent'-property case ... is handled for a
  21.         // property that is not an array or object
  22.         if (typeof prop != 'object') {
  23.             arr.push(prop);
  24.         } else {
  25.             arr.push(prop[i]);
  26.         }
  27.     }
  28.  
  29.     // alert the demo array
  30.     alert('[' + arr + '] :: length = ' + arr.length);
  31. }
  32.  
kind regards

ps: note that i made URI to a string (for testing purposes) and you had a syntax error in your original post in line 13 ... the brackets have to be switched :)
Nov 13 '07 #2
RMWChaos
137 New Member
Hey again, gits!

Ok, I am trying to understand your code here. Do you recall my post from a couple days ago, the one you replied to with that mass of code to go through (dom attributes vs. javascript attributes)?

Hover Scripts Work in FF & NN, but not IE

Well, createDOM is a function that creates a DOM element (or elements in this case) using the values from a JSON property list; so my goal is basically to take several property lists like this:

Expand|Select|Wrap|Line Numbers
  1. createDOM ({
  2.   'id'     :    "idname1",
  3.   'dom'    :    "domtype1",
  4.   'parent' :    "parentname"
  5.   });
  6.  
  7. createDOM ({
  8.   'id'     :    "idname2",
  9.   'dom'    :    "domtype2",
  10.   'parent' :    "parentname"
  11.   });
  12.  
...and turn it into a single list like this:

Expand|Select|Wrap|Line Numbers
  1. createDOM ({
  2.   'id'     :    ["idname", "idname2"],
  3.   'dom'    :    ["domtype", "domtype2"],
  4.   'parent' :    "parentname"
  5.   });
  6.  
So all I need to know at this point is how to iterate through the list using the next value for each object every loop. Does that clarify my original question?

My second example in my original post does accomplish this goal, but it's not very graceful. Maybe it's something like createDOM.id[0] and [1] in the example above, or perhaps attrib.id[0] access the first value of the first property using my createDOM script.

So if that is the case, I can modify my createDOM script to do a "while attrib.id has child nodes", or if that doesn't work a check for attrib.id[x] using for (x >= 0; x < attrib.index[0].length; x++). Hm, that might work.
Nov 14 '07 #3
gits
5,390 Recognized Expert Moderator Expert
hi ...

lets have a closer look at my example and adapt it slightly to match your needs:

Expand|Select|Wrap|Line Numbers
  1. var your_data = {
  2.     'id'      :   ["formname", "inputname", "submitbutton"],
  3.     'dom'     :   ["form", "input", "input"],
  4.     'parent'  :   "content",
  5.     'form'    :   [null, "formname", "formname"],
  6.     'action'  :   ['URI', null, null],
  7.     'method'  :   ["post", null, null],
  8.     'type'    :   [null, null, "submit"],
  9.     'size'    :   [null, 6, null],
  10.     'value'   :   [null, null, "Submit"]
  11. };
  12.  
  13. function createDOMfromList(data) {
  14.     for (var i = 0; i < 3; i++) {
  15.         var obj = {};
  16.  
  17.         for (var j in data) {
  18.             var prop = data[j];
  19.  
  20.             obj[j] = prop instanceof Array ? prop[i] : prop;
  21.         }
  22.  
  23.         createDOM(obj);
  24.     }
  25. }
  26.  
  27. function createDOM(obj) {
  28.     alert(obj.toSource());
  29. }
  30.  
  31. createDOMfromList(your_data);
  32.  
as you can see ... its easy to use for your purpose, we create a new function that receives the list and calls you current method ... test it in FF because the toSource() won't work in IE ... but its only for demo of the createDOM() call :)

kind regards
Nov 14 '07 #4
RMWChaos
137 New Member
Ok, I think I got it now.

So to modify this a bit, I could recode my createDOM script to include this:

Expand|Select|Wrap|Line Numbers
  1. function createDOMfromList(data)
  2.     {
  3.     // because 'id' is required in my createDOM script, it determines
  4.     // the total number of values (DOM elements) to create; so instead
  5.     // of i < #, I can do this:
  6.     for (var i = 0; i < data[id].length; i++)
  7.         {
  8.         var obj = {};
  9.         for (var j in data)
  10.             {
  11.             var prop = data[j];
  12.             obj[j] = prop instanceof Array ? prop[i] : prop;
  13.             };
  14.             createDOM(obj);
  15.        };
  16.    };
  17.  
And then my property lists change to this:
Expand|Select|Wrap|Line Numbers
  1. createDOMfromList({
  2.     'id'      :   ["formname", "inputname", "submitbutton"],
  3.     'dom'     :   ["form", "input", "input"],
  4.     'parent'  :   "content",
  5.     etc...
  6.     });
  7.  
It adds an extra function, which is not really a problem, but I wonder if I can integrate the two into one? Anyway, I will try out what you have given me and work from there.

Thanks again!



[thinking out loud]
//no need to respond to this next part...just a reminder to myself

I also need to test to see what type of behavior to expect if there is a mismatch in the number of members in each value list. So if 'id' had 3 members, but 'parent' had only 2 members, what would be the result? In this case, my createDOM script has a default value for 'dom' and 'parent'; so I am pretty sure what the result would be there, but what if there were no default value, such as 'name' or 'type'. Would it error out, use the last value member repeatedly, use null?

And is it better to use null as a spaceholder for empty values, or "", or nothing at all, just back-to-back commas to separate empty values (i.e. [value1,,value3, ,,value6]). Guess I will find out.

[/thinking out loud]
Nov 14 '07 #5
gits
5,390 Recognized Expert Moderator Expert
good luck with it ... :)

btw: in case you refer to an nonexistent element in an array you will get it as 'undefined' ... so you could use the following check to set a default value in such a case:

Expand|Select|Wrap|Line Numbers
  1. if (typeof value == 'undefined') {
  2.     value = null;
  3. }
kind regards
Nov 14 '07 #6
RMWChaos
137 New Member
...you could use the following check to set a default value in such a case:
Expand|Select|Wrap|Line Numbers
  1. if (typeof value == 'undefined')
  2.     {
  3.     value = null;
  4.     };
  5.  
The problem with that is I already use this code:
Expand|Select|Wrap|Line Numbers
  1. for (var index in defaultAttribs)
  2.     {
  3.     if(typeof attrib[index] == 'undefined')
  4.         {
  5.         attrib[index] = defaultAttribs[index];
  6.         };
  7.     };
  8.  
And I set defaultAttribs in a seperate JSON property list. I would rather the code simply ignore 'undefined' values that do not have a default, and not even include them in the DOM creation process. I'll think on that a while. It shouldn't matter whether the attribute is 'undefined' or null should it? It won't affect the element in any way, I don't think. I guess I could just leave it alone; I haven't seen any issues with it so far.
Nov 14 '07 #7
gits
5,390 Recognized Expert Moderator Expert
you are right in case i understand it right that you don't create an attribute when there is no value for it ... otherwise it could be a problem with attributes that are such ones that only have to be present like:

[HTML]<input type="text" name="test" readonly="whate ver_value"/>[/HTML]
so in such a case it would matter when simply creating the readonly attribute (with null or undefined or even whatever_value) because the browser simply checks for its existence ... so make the element editable the attribute mustn't exist ... so in case you handle it the 'leave-it-out-way' you wouldn't encounter problems with that ... otherwise it could be a problem ... :)
Nov 14 '07 #8
RMWChaos
137 New Member
you are right in case i understand it right that you don't create an attribute when there is no value for it...
Correct, if the attribute does not exist in the either the attrib or defaultAttribs list, then it will not be created at all. So that is not an issue when I am working with a single value for each object. However, when I am setting multiple values for each object, many of them will be null or 'undefined' unless I am creating the same type of DOM element all the time (unlikely). That is where I want to make sure that null or 'undefined' values will not be a problem, and I believe that it is not.
...so make the element editable the attribute mustn't exist ... so in case you handle it the 'leave-it-out-way' you wouldn't encounter problems with that ... otherwise it could be a problem ... :)
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.

So how would it be a problem? And should I create a filter that removes/ignores objects when the value is null or 'undefined'. How would I say, "if ((value == null) || (typeof value == 'undefined')) skip it and go to the next value"? Oh, duh. It would actually be "if ((value != null) || (typeof value != 'undefined')) set the attib". Otherwise, it would ignore it and move on to the next value...I think.
Nov 14 '07 #9
RMWChaos
137 New Member
Woo-hoo! It works!

I ended up going with this code:
Expand|Select|Wrap|Line Numbers
  1. function createDOM(attribList) // Create DOM Elements Function //
  2.     {
  3.     for (var i = 0; i < attribList.id.length; i++) // iterate through multiple values //
  4.         {
  5.         var attrib = {};
  6.         for (var index in attribList) // assign attribList values to attrib //
  7.             {
  8.             if ((attribList[index] != null) && (typeof attribList[index] != 'undefined')) // filter out null & 'undefined' values //
  9.                 {
  10.                 var value = attribList[index];
  11.                 attrib[index] = value instanceof Array ? value[i] : value;
  12.                 };
  13.             };
  14.         };
  15.     var defaultAttribs =
  16.         {
  17.         'dom'        :    'div',
  18.         'parent'    :    'body'
  19.         };
  20.     for (index in defaultAttribs) // Assign default attribs to 'undefined' values//
  21.         {
  22.         if(typeof attrib[index] == 'undefined')
  23.             {
  24.             attrib[index] = defaultAttribs[index];
  25.             };
  26.         };
  27. etc...
  28.  
It remains a single function, I don't have to change any of the rest of my createDOM() function, and I don't have to make any changes to my other scripts which call createDOM(). In this particular order, the code iterates through multiple values, ignores null and 'undefined' values (shouldn't be a problem, right?), and then sets default values to required 'undefined' values.

Thank you very much for your help, once again, gits.
Nov 14 '07 #10

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

Similar topics

2
5238
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
7730
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
2822
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
3826
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
2348
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
9645
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
10341
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10095
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
8979
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7502
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5513
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4054
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3656
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2881
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.