├── LICENSE ├── README.md ├── bower.json ├── dist ├── jquery.serializeToJSON.js └── jquery.serializeToJSON.min.js ├── example └── exemple 1.html ├── package.json └── src └── jquery.serializeToJSON.js /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 raphaelm22 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # jquery.serializeToJSON 2 | 3 | 4 | Adds the method `.serializeToJSON()` to [jQuery](http://jquery.com/) that Serialize an HTML form (familiar with ASP MVC) to a JavaScript object, supporting nested attributes and arrays. 5 | 6 | Install 7 | ------- 8 | 9 | Install with [bower](http://bower.io/) `bower install jquery.serializeToJSON`, or [npm](https://www.npmjs.com/) `npm install jquery-serializetojson'`, or just download the [jquery.serializetojson.js](https://github.com/raphaelm22/jquery.serializeToJSON/raw/master/src/jquery.serializeToJson.js) script. 10 | 11 | And make sure it is included after jQuery, for example: 12 | ```html 13 | 14 | 15 | ``` 16 | 17 | Usage Example 18 | ------------- 19 | 20 | HTML form (input, textarea and select tags supported): 21 | 22 | ```html 23 | 24 |
99 | 100 | ``` 101 | 102 | JavaScript: 103 | 104 | ```javascript 105 | var obj = $("#myForm").serializeToJSON({ 106 | parseFloat: { 107 | condition: ".number,.money" 108 | } 109 | }); 110 | 111 | // obj => 112 | { 113 | Customer: { 114 | FullName: "Raphael Nunes", 115 | Email: "myemail@gmail.com" 116 | }, 117 | Payment: "1", 118 | CreditCardCompany: [ 119 | "Company A", 120 | "Company C" 121 | ], 122 | IsNewCustomer: true, 123 | ReceiveEmailPartner: false, 124 | ReceiveSMSPartner: false, 125 | Product: { 126 | 0: { 127 | ID: 54457, 128 | Name: "Smartphone", 129 | Quantity: 5, 130 | Cost: 1,054.99 131 | }, 132 | 1: { 133 | ID: 97518, 134 | Name: "iPad", 135 | Quantity: 3, 136 | Cost: 2,119.99 137 | } 138 | } 139 | } 140 | 141 | var objNotAssociativeArrays = $("#myForm").serializeToJSON({associativeArrays: false}); 142 | // objNotAssociativeArrays => 143 | { 144 | Customer: { 145 | "FullName": "Raphael Nunes", 146 | "Email": "myemail@gmail.com" 147 | }, 148 | Payment: "1", 149 | CreditCardCompany: [ 150 | "Company A", 151 | "Company C" 152 | ], 153 | IsNewCustomer: true, 154 | ReceiveEmailPartner: false, 155 | ReceiveSMSPartner: false, 156 | Product: [ 157 | { 158 | ID: "54457", 159 | Name: "Smartphone", 160 | Quantity: "5", 161 | Cost: "1,054.99" 162 | }, 163 | { 164 | ID: "97518", 165 | Name: "iPad", 166 | Quantity: "3", 167 | Cost: "2,119.99" 168 | } 169 | ] 170 | } 171 | ``` 172 | 173 | The function `serializeToJSON` return a JavaScript object, not a JSON string. 174 | 175 | If you want a chain a JSON string then use `JSON.stringify` 176 | To support old browsers, just include the [json2.js](https://github.com/douglascrockford/JSON-js) polyfill (as described on [stackoverfow](http://stackoverflow.com/questions/191881/serializing-to-json-in-jquery)). 177 | 178 | ```javascript 179 | var obj = $("#myForm").serializeToJSON(); 180 | var jsonString = JSON.stringify(obj); 181 | ``` 182 | 183 | Note that `.serializeToJSON ()` uses the return of jQuery's method [.serializeArray ()] (https://api.jquery.com/serializeArray/) to create the serialized object. 184 | So if the return is not desired, first check that that was returned by the [.serializeArray ()] (https://api.jquery.com/serializeArray/) method. 185 | 186 | 187 | Options 188 | ------- 189 | 190 | To change the default options, simply enter the desired options via parameter of the method `.serializeToJSON ()`. 191 | 192 | To change the default behavior you use the following options: 193 | 194 | * **associativeArrays: true**, by default, the method does not serialize using the `Array` but `Associative Arrays`. 195 | 196 | * **parseBooleans: true**, automatically detect and convert strings `"true"` and `"false"` to booleans `true / false`. 197 | 198 | * **parseFloat.condition: undefined**, the value can be a `string` or `function` 199 | 200 | **`string`**: filter used in the function [`jQuery().is('condition')`] (http://api.jquery.com/is/) to detect and convert into float / number. Example: `".number"` or `"[mask='money']"`. 201 | 202 | **`function`**: the return of function sets when the convert occur. example: 203 | ```javascript 204 | function(i) { 205 | var v = i.val().split(",").join(""); 206 | return !isNaN(Number(v)); // In this case, conversion will always occur when possible 207 | } 208 | ``` 209 | 210 | * **parseFloat.nanToZero: true**, automatically detect `NaN` value and changes the value to zero. 211 | 212 | * **parseFloat.getInputValue: `function(){}`**, By default, returns the input value without commas, not an error occurs in conversion. 213 | if your location uses comma for decimal separation, for example in German or Brazil, you can change to: 214 | ```javascript 215 | function(i){ 216 | return i.val().split(".").join("").replace(",", "."); 217 | } 218 | ``` 219 | 220 | 221 | 222 | ## Defaults ## 223 | 224 | All options defaults are defined in `$.serializeToJSON.defaultOptions`. You can just modify it to avoid setting the option on every call to `serializeToJSON`. 225 | 226 | For example: 227 | 228 | ```javascript 229 | $.fn.serializeToJSON.defaults.parseBooleans = false; // not parse booleans by default 230 | $.fn.serializeToJSON.defaults.associativeArrays = false; // not use associative array by default 231 | 232 | $("#myForm").serializeToJSON(); // No options => then use $.fn.serializeToJSON.defaults 233 | ``` 234 | 235 | Contributions 236 | ------------- 237 | 238 | Contributions are always welcome. 239 | 240 | 241 | Author 242 | ------- 243 | 244 | Written and maintained by [Raphael Nunes](https://github.com/raphaelm22) 245 | 246 | 247 | -------------------------------------------------------------------------------- /bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "jquery.serializeToJSON", 3 | "description": "Add the method .serializeToJSON() to jQuery that Serialize a HTML form (familiar with ASP MVC), supporting nested attributes and arrays.", 4 | "keywords": [ 5 | "form", 6 | "serialize", 7 | "json", 8 | "helper", 9 | "jquery", 10 | "asp", 11 | "mvc" 12 | ], 13 | "authors": [ 14 | "Raphael Nunes" 15 | ], 16 | "license": "MIT", 17 | "homepage": "https://github.com/raphaelm22/jquery.serializeToJSON", 18 | "repository": { 19 | "type": "git", 20 | "url": "git://github.com/raphaelm22/jquery.serializeToJSON.git" 21 | }, 22 | "ignore": [ 23 | "**/.*", 24 | "node_modules", 25 | "bower_components", 26 | "test", 27 | "tests" 28 | ] 29 | } 30 | -------------------------------------------------------------------------------- /dist/jquery.serializeToJSON.js: -------------------------------------------------------------------------------- 1 | /** 2 | * serializeToJSON jQuery plugin 3 | * https://github.com/raphaelm22/jquery.serializeToJSON 4 | * @version: v1.4.1 (October, 2019) 5 | * @author: Raphael Nunes 6 | * 7 | * Created by Raphael Nunes on 2015-08-28. 8 | * 9 | * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 10 | */ 11 | 12 | (function (factory) { 13 | if (typeof define === 'function' && define.amd) { 14 | define(['jquery'], factory); 15 | } else if (typeof module === 'object' && module.exports) { 16 | module.exports = function( root, jQuery ) { 17 | if ( jQuery === undefined ) { 18 | if ( typeof window !== 'undefined' ) { 19 | jQuery = require('jquery'); 20 | } 21 | else { 22 | jQuery = require('jquery')(root); 23 | } 24 | } 25 | factory(jQuery); 26 | return jQuery; 27 | }; 28 | } else { 29 | factory(jQuery); 30 | } 31 | }(function ($) { 32 | 'use strict'; 33 | 34 | $.fn.serializeToJSON = function(options) { 35 | 36 | var f = { 37 | settings: $.extend(true, {}, $.fn.serializeToJSON.defaults, options), 38 | 39 | getValue: function($input) { 40 | var value = $input.val(); 41 | 42 | if ($input.is(":radio")) { 43 | value = $input.filter(":checked").val() || null; 44 | } 45 | 46 | if ($input.is(":checkbox")) { 47 | value = $($input).prop('checked'); 48 | } 49 | 50 | if (this.settings.parseBooleans) { 51 | var boolValue = (value + "").toLowerCase(); 52 | if (boolValue === "true" || boolValue === "false") { 53 | value = boolValue === "true"; 54 | } 55 | } 56 | 57 | var floatCondition = this.settings.parseFloat.condition; 58 | if (floatCondition !== undefined && ( 59 | (typeof(floatCondition) === "string" && $input.is(floatCondition)) || 60 | (typeof(floatCondition) === "function" && floatCondition($input)))) { 61 | 62 | value = this.settings.parseFloat.getInputValue($input); 63 | value = Number(value); 64 | 65 | if (this.settings.parseFloat.nanToZero && isNaN(value)){ 66 | value = 0; 67 | } 68 | } 69 | 70 | return value; 71 | }, 72 | 73 | createProperty: function(o, value, names, $input) { 74 | var navObj = o; 75 | 76 | for (var i = 0; i < names.length; i++) { 77 | var currentName = names[i]; 78 | 79 | if (i === names.length - 1) { 80 | var isSelectMultiple = $input.is("select") && $input.prop("multiple"); 81 | 82 | if (isSelectMultiple && value !== null){ 83 | navObj[currentName] = new Array(); 84 | 85 | if (Array.isArray(value)){ 86 | $(value).each(function() { 87 | navObj[currentName].push(this); 88 | }); 89 | } 90 | else{ 91 | navObj[currentName].push(value); 92 | } 93 | } else if(typeof navObj[currentName] !== "undefined"){ 94 | if (!$input.is("[type='hidden']")) 95 | navObj[currentName] = value; 96 | } else { 97 | navObj[currentName] = value; 98 | } 99 | } else { 100 | var arrayKey = /\[\w+\]/g.exec(currentName); 101 | var isArray = arrayKey != null && arrayKey.length > 0; 102 | 103 | if (isArray) { 104 | currentName = currentName.substr(0, currentName.indexOf("[")); 105 | 106 | if (this.settings.associativeArrays) { 107 | if (!navObj.hasOwnProperty(currentName)) { 108 | navObj[currentName] = {}; 109 | } 110 | } else { 111 | if (!Array.isArray(navObj[currentName])) { 112 | navObj[currentName] = new Array(); 113 | } 114 | } 115 | 116 | navObj = navObj[currentName]; 117 | 118 | var keyName = arrayKey[0].replace(/[\[\]]/g, ""); 119 | currentName = keyName; 120 | } 121 | 122 | if (!navObj.hasOwnProperty(currentName)) { 123 | navObj[currentName] = {}; 124 | } 125 | 126 | navObj = navObj[currentName]; 127 | } 128 | } 129 | }, 130 | 131 | includeUncheckValues: function(selector, formAsArray){ 132 | $(":radio", selector).each(function(){ 133 | var isUncheckRadio = $("input[name='" + this.name + "']:radio:checked").length === 0; 134 | if (isUncheckRadio) 135 | { 136 | formAsArray.push({ 137 | name: this.name, 138 | value: null 139 | }); 140 | } 141 | }); 142 | 143 | $("select[multiple]", selector).each(function(){ 144 | if ($(this).val() === null){ 145 | formAsArray.push({ 146 | name: this.name, 147 | value: null 148 | }); 149 | } 150 | }); 151 | }, 152 | 153 | //clone of the jquery method, but returns the element 154 | serializeArray: function(formSelector) { 155 | var rCRLF = /\r?\n/g, 156 | rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, 157 | rsubmittable = /^(?:input|select|textarea|keygen)/i, 158 | rcheckableType = ( /^(?:checkbox|radio)$/i ); 159 | 160 | return formSelector.map(function() { 161 | var elements = jQuery.prop( this, "elements" ); 162 | return elements ? jQuery.makeArray( elements ) : this; 163 | }) 164 | .filter( function() { 165 | var type = this.type; 166 | return this.name && !jQuery( this ).is( ":disabled" ) && 167 | rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && 168 | ( this.checked || !rcheckableType.test( type ) ); 169 | }) 170 | .map( function( i, elem ) { 171 | var val = jQuery( this ).val(); 172 | 173 | if ( val == null ) return null; 174 | 175 | if ( Array.isArray( val ) ) { 176 | return jQuery.map( val, function( val ) { 177 | return { name: elem.name, value: val.replace( rCRLF, "\r\n" ), elem: elem }; 178 | } ); 179 | } 180 | 181 | return { name: elem.name, value: val.replace( rCRLF, "\r\n" ), elem: elem }; 182 | }).get(); 183 | }, 184 | 185 | serializer: function(selector) { 186 | var self = this; 187 | 188 | var formAsArray = this.serializeArray($(selector)); 189 | this.includeUncheckValues(selector, formAsArray); 190 | 191 | var serializedObject = {} 192 | 193 | for (var prop in formAsArray) { 194 | if(formAsArray.hasOwnProperty( prop )) { 195 | var item = formAsArray[prop]; 196 | 197 | var $input = $(item.elem); 198 | 199 | var value = self.getValue($input); 200 | var names = item.name.split("."); 201 | 202 | self.createProperty(serializedObject, value, names, $input); 203 | } 204 | } 205 | return serializedObject; 206 | } 207 | }; 208 | 209 | return f.serializer(this); 210 | }; 211 | 212 | $.fn.serializeToJSON.defaults = { 213 | associativeArrays: true, 214 | parseBooleans: true, 215 | parseFloat: { 216 | condition: undefined, 217 | nanToZero: true, 218 | getInputValue: function($input){ 219 | return $input.val().split(",").join(""); 220 | } 221 | } 222 | }; 223 | })); -------------------------------------------------------------------------------- /dist/jquery.serializeToJSON.min.js: -------------------------------------------------------------------------------- 1 | // jQuery SerializeToJSON v1.4.1 2 | // github.com/raphaelm22/jquery.serializeToJSON 3 | !function(e){"function"==typeof define&&define.amd?define(["jquery"],e):"object"==typeof module&&module.exports?module.exports=function(r,t){return void 0===t&&(t="undefined"!=typeof window?require("jquery"):require("jquery")(r)),e(t),t}:e(jQuery)}(function(e){"use strict";e.fn.serializeToJSON=function(r){var t={settings:e.extend(!0,{},e.fn.serializeToJSON.defaults,r),getValue:function(r){var t=r.val();if(r.is(":radio")&&(t=r.filter(":checked").val()||null),r.is(":checkbox")&&(t=e(r).prop("checked")),this.settings.parseBooleans){var n=(t+"").toLowerCase();"true"!==n&&"false"!==n||(t="true"===n)}var i=this.settings.parseFloat.condition;return void 0!==i&&("string"==typeof i&&r.is(i)||"function"==typeof i&&i(r))&&(t=this.settings.parseFloat.getInputValue(r),t=Number(t),this.settings.parseFloat.nanToZero&&isNaN(t)&&(t=0)),t},createProperty:function(r,t,n,i){for(var a=r,s=0;s