简体   繁体   English

在javascript中创建一个Json对象

[英]Create a Json object in javascript

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. 我正在验证一个表单,我需要显示某些单选按钮,用户需要根据一些规则选择它们,可以创建多少个单选按钮是动态的,所以我不能在服务器端进行验证不能写一个预定义的java脚本代码。

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 每个单选按钮将被分成required组,而不是向下,它们可以分组为centerleftright等,所以从每个组用户需要选择一个值,所以结构就像这样

-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 我打算在页面渲染时创建一个JSON对象

{"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? 我不确定我认为的结构是否正确以及如何在java脚本中创建它? 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. 但不知道如何创建一个正确的结构,以便我可以稍后用jquery解析它并使用它进行验证。

Any help in this will really be appreciated. 任何帮助都将非常感激。

In javascript. 在javascript中。 You can use JSON.stringify(myObject, replacer); 您可以使用JSON.stringify(myObject, replacer);

For example. 例如。

create on javascript object like this 像这样在javascript对象上创建

var myObject={};

now after creating javascript object you can convert it into JSON structure like this 现在,在创建javascript对象后,您可以将其转换为JSON结构

var myJsonText=JSON.stringify(myObject);

NOTE: replacer is optional 注意:替换器是可选的

Now if you want to convert it in JSON Object Use JSON.parse method 现在,如果要在JSON对象中转换它,请使用JSON.parse方法

myJsonObject=JSON.parse(myJsonText)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM