Create a Json object in javascript

I am in the process of checking the form where I need to show certain switches, and the user needs to select them based on some rules, how many radio windows will be created, so I canโ€™t perform the server side check, I canโ€™t write the predefined java-script code for this.

each of the switches will be divided into groups that say required , and the further they can be grouped as center , left , right , etc., so the user needs to choose one value from each group, so the structure looks like this:

 -Main Group (if block needs to validate based on this eg if key=required should validate) | Sub-group (say left, right etc) | number of radio buttons based on the sub-group 

Thus, the main group key can be used to decide whether to validate on this issue or not, and based on the subgroup key, I can decide what all the values โ€‹โ€‹will be there and what needs to be checked.

i planned to create a JSON object while the page was being rendered, for example

 {"required": [ {"center": "id1,id2,id3"}, {"left": "id1,id2,id3"} ] "optional": [ {"center": "id1,id2,id3"}, {"left": "id1,id2,id3"} ] }; 

I'm not sure if the structure I think of is correct and how to create it in a java script? for example, I have an outer loop for a key and another loop for a subgroup and finally for buttons in a subgroup,

  for(main group key){ for(subgroup key){ for(list of radio button under subgroup key) } } 

but not sure how to create the correct structure so that I can parse it later using jquery and use for validation.

Any help on this would really be appreciated.

+6
source share
1 answer

In javascript. You can use JSON.stringify(myObject, replacer);

For instance.

create a javascript object like this

 var myObject={}; 

now after creating the javascript object you can convert it to a JSON structure like this

 var myJsonText=JSON.stringify(myObject); 

NOTE: substitute is optional.

Now, if you want to convert it to a JSON Object Use the JSON.parse method

 myJsonObject=JSON.parse(myJsonText) 
+4
source

Source: https://habr.com/ru/post/925481/


All Articles