Convert data of form serialization type into processing objects (including objects allowed) based on JavaScript, and serialize javascript data

Source: Internet
Author: User

Convert data of form serialization type into processing objects (including objects allowed) based on JavaScript, and serialize javascript data

Data of the form serialization type refers to the format of data transmitted by the url, such as key/value pairs such as "key = value & key = value. In general, the $. fn. serialize function of jQuery can achieve this effect. How to convert such a format to an object?

We know that the $. fn. serializeArray function of jQuery produces an object with the following structure:

[  {    name: "startTime"    value: "2015-12-02 00:00:00"  },  {    name: "endTime"    value: "2015-12-25 23:59:59"  }]

This is an array of objects, but sometimes we want to get an object with the following structure:

{  "startTime": "2015-12-02 00:00:00"  "endTime": "2015-12-25 23:59:59"}

So here we need a conversion function.

The procedure is as follows:

1. Separate each key-value pair with "&" and then process each key-Value Pair cyclically

Var properties = serializedParams. split ("&"); for (var I = 0; I <properties. length; I ++) {// process each key-Value Pair evalThem (properties [I]);};

2. Split the specified key-value pair from the "=" symbol and use decodeURIComponent to parse the uri component encoding for each key and value (because the serialized data transmitted by the url is generally encoded by the uri component)

Var strAry = new Array (); strAry = str. split ("="); // use decodeURIComponent to parse uri component encoding for (var I = 0; I <strAry. length; I ++) {strAry [I] = decodeURIComponent (strAry [I]);} var attributeName = strAry [0]; var attributeValue = strAry [1]. trim ();

3. If the value contains the "=" symbol, additional processing is required (value merging ).

 if(strAry.length > 2){      for(var i = 2;i<strAry.length;i++){        attributeValue += "="+strAry[i].trim();      }    } 

There is a processing process here, that is, when the value does not exist, it will not be added to the final object. You can choose whether to delete the code as needed.

   if(!attributeValue){      return ;    } 

4. If the key is linked by the "." symbol like "obj. obj. obj", it must be processed as an object containing the object. The processing method is to break down the key through ".", and then check whether the temporary object obj contains the decomposed object. If yes, the data is appended to the existing object. The source code is as follows:

 var attriNames = attributeName.split("."),      curObj = obj;    for(var i = 0; i < (attriNames.length - 1); i++){      curObj[attriNames[i]]?"":(curObj[attriNames[i]] = {});      curObj = curObj[attriNames[i]];    }    curObj[attriNames[i]] = attributeValue.trim(); 

Here we can see that the assignment part on the internet is handled in this way.

eval("obj."+attributeName+"=\""+attributeValue.trim()+"\";"); 

This is very problematic. One is that it cannot correctly handle the problem of object inclusion in object 4 (especially when two elements have the same parent object, such as "test. id = 1 & test. name = 'chuna' "all have the parent object test ). The other is that attributeValue cannot be correctly processed when it contains single quotation marks or double quotation marks. Therefore, "=" is the safest option.

The complete source code is as follows:

/* The serializedParams format is "key1 = value1 & key2 = value2 ". the 'key. sonkey = value '*/function paramString2obj (serializedParams) {var obj ={}; function evalThem (str) {var strAry = new Array (); strAry = str. split ("="); // use decodeURIComponent to parse uri component encoding for (var I = 0; I <strAry. length; I ++) {strAry [I] = decodeURIComponent (strAry [I]);} var attributeName = strAry [0]; var attributeValue = strAry [1]. trim (); // if the value is Contains the "=" symbol, and the value if (strAry. length> 2) {for (var I = 2; I <strAry. length; I ++) {attributeValue + = "=" + strAry [I]. trim () ;}} if (! AttributeValue) {return;} var attriNames = attributeName. split (". "), curObj = obj; for (var I = 0; I <(attriNames. length-1); I ++) {curObj [attriNames [I]? "" :( CurObj [attriNames [I] ={}); curObj = curObj [attriNames [I];} // use the value assignment method obj [attributeName] = attributeValue. trim (); replace // eval ("obj. "+ attributeName +" = \ "" + attributeValue. trim () + "\"; "); // solves the problem that the attributeValue cannot be processed when it contains single quotation marks or double quotation marks. curObj [attriNames [I] = attributeValue. trim () ;}; var properties = serializedParams. split ("&"); for (var I = 0; I <properties. length; I ++) {// process each key value pair evalThem (properties [I]);}; return obj ;}

The above content is based on JavaScript to convert form serialized data into object processing (allowing objects to contain objects). I hope this article will help you.

Articles you may be interested in:
  • JQuery-serialize () method for outputting serialized form values
  • How jquery serializes a form into an object
  • How jquery serializes a form into an object
  • Verify the form submission method and implement serialized Form Content in jQuery
  • Example of using form serialization and serialize in jq
  • Jquery serialized form json data returned after ajax submission
  • How to serialize form elements into json objects using jQuery
  • Getting box values and serialization of forms in js forms

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.