Create a Json object in javascript

13,804

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

For example.

create on javascript object like this

var myObject={};

now after creating javascript object you can convert it into JSON structure like this

var myJsonText=JSON.stringify(myObject);

NOTE: replacer is optional

Now if you want to convert it in JSON Object Use JSON.parse method

myJsonObject=JSON.parse(myJsonText)
Share:
13,804
Umesh Awasthi
Author by

Umesh Awasthi

Updated on July 01, 2022

Comments

  • Umesh Awasthi
    Umesh Awasthi over 1 year

    I am in process to validate a form where i need to show certain radio buttons and user need to select them based on some rules,how many number of radio buttons can be created is dynamic so i can not do validation on server side not can write a predefined java-script code for that.

    each of the radio buttons will be divided in to groups say required and than further down they can be grouped like center,left, right etc, so from each group user need to select one value, so the structure comes out like this

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

    So the main group key can be used to decide if validation should be done on that or not and based on the sub-group key i can decide what all values will be there and needs to be validate

    i was planning to create a JSON object on page rendering time like

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

    i am not sure if the structure i am thinking is right and how to create it in java script? like i have a external loop for key and than one more loop for the sub-group and finally for the buttons in the sub-group,

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

    but not sure how to create a right structure so that i can parse it later with jquery and use that for validation.

    Any help in this will really be appreciated.