Jquery Serialize Object

XML data

by B L Praveen

HTML

<form>
    <input name="cols[]" value="col1"/>
    <input name="cols[]" value="col2"/>
    <input name="row[row1][]" value="one"/>
    <input name="row[row1][]" value="two"/>
    <input name="row[row2][]" value="three"/>
    <input name="row[row2][]" value="four"/>
</form>

<h1>Serializes as</h1>
<div id="output"></div>
<textarea id="output_xml"></textarea

JavaScript

// Add function to jQuery namespace
		 $.extend({ 
		  // converts xml documents and xml text to json object
		  json2xml: function(jsonObj,config) {
			config = config || {};
			initConfigDefaults();
			
			var out = parseJSONObject(jsonObj);
			return out;
			function initConfigDefaults() {
				if(config.escapeMode === undefined) {
					config.escapeMode = true;
				}
				config.attributePrefix = config.attributePrefix || "_";
				config.arrayAccessForm = config.arrayAccessForm || "none";
				config.emptyNodeForm = config.emptyNodeForm || "text";
				if(config.enableToStringFunc === undefined) {
					config.enableToStringFunc = true; 
				}
				config.arrayAccessFormPaths = config.arrayAccessFormPaths || []; 
				if(config.skipEmptyTextNodesForObj === undefined) {
					config.skipEmptyTextNodesForObj = true;
				}
				if(config.stripWhitespaces === undefined) {
					config.stripWhitespaces = true;
				}
				config.datetimeAccessFormPaths = config.datetimeAccessFormPaths || [];
			}	
			function startTag(jsonObj, element, attrList, closed) {
				var resultStr = "<"+ ( (jsonObj!=null && jsonObj.__prefix!=null)? (jsonObj.__prefix+":"):"") + element;
				if(attrList!=null) {
					for(var aidx = 0; aidx < attrList.length; aidx++) {
						var attrName = attrList[aidx];
						var attrVal = jsonObj[attrName];
						if(config.escapeMode)
							attrVal=escapeXmlChars(attrVal);
						resultStr+=" "+attrName.substr(config.attributePrefix.length)+"='"+attrVal+"'";
					}
				}
				if(!closed)
					resultStr+=">";
				else
					resultStr+="/>";
				return resultStr;
			}
			
			function endTag(jsonObj,elementName) {
				return "</"+ (jsonObj.__prefix!=null? (jsonObj.__prefix+":"):"")+elementName+">";
			}
			
			function endsWith(str, suffix) {
				return str.indexOf(suffix, str.length - suffix.length) !== -1;
			}
			function getNodePrefix(node) {
				return node.prefix;
			}
				
			function escapeXmlChars(str) {
				if(typeof(str) == "string")
					return...