项目作者: NickMaev

项目描述 :
Vanilla js JSON form serializer
高级语言: HTML
项目地址: git://github.com/NickMaev/NSerializeJson.git
创建时间: 2018-09-20T14:00:20Z
项目社区:https://github.com/NickMaev/NSerializeJson

开源协议:MIT License

下载


``` HTML form (dot separator): ```html
``` JavaScript: ```typescript NSerializeJson.serializeForm(document.getElementById("my-profile") as HTMLFormElement) // returns => { fullName: "Nikolay Maev", address: { city: "Rostov-on-Don", state: { name: "Rostov oblast'", abbr: "ROV" } }, jobbies: ["coding", "cycling"], projects: { '0': { name: "NVal", language: "TypeScript", popular: "1" }, '1': { name: "NSerializeJson", language: "TypeScript", popular: "0" } }, selectOne: "rock", selectMultiple: ["red", "blue"] } ``` The `serializeForm` function returns a JavaScript object, not a JSON String. Parse values with :types ------------------------ All attribute values are **auto** by default. But you can force values to be parsed with specific types by appending the type with a colon. ```html
``` ```typescript NSerializeJson.serializeForm(document.getElementById("myForm") as HTMLFormElement); // returns => { "strbydefault": ":string is the default (implicit) type", "text": ":string type can still be used to override other parsing options", "numbers": [ 0, 1 ], "keys": { "1.1": 1.1 }, "bools": { "true": true, "false": false, "zero": false }, "autos": { "string": "text with stuff", "one": 1, "two": 2, "true": true, "false": false, "null": null, "list": [ 1, 2, 3, "foo", "bar", { "pet": "cat" } ] }, "arrays": { "empty": [], "auto": [ 1, 2, 3, "foo", "bar" ], "numbers": [ 1, 2, 3, null, // <-- Non-digit. null // <-- Non-digit. ] }, "json": { "empty": {}, "not empty": { "my": "stuff" } } } ``` Types can also be specified with the attribute `data-value-type`, instead of having to add the ":type" suffix: ```html
``` ## Options By default `.serializeForm()` with default options has this behavior: * Values are always **auto** (unless appending :types to the input names) * Unchecked checkboxes are ignored (as defined in the W3C rules for [successful controls](http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2)). * Disabled elements are ignored (W3C rules) * String keys are always **string** except the numbers Allowed options `NSerializeJson.options` to change the default behavior: * **forceNullOnEmpty: false**, if true, will record `null` instead of empty value. Otherwise, records empties (`""`, `0`, `false`). * **useDotSeparatorInPath: false**, if true allows you to use the dot notation instead of brackets in the name attribute (i.e. ``). * **useNumKeysAsArrayIndex: true**, when using integers as keys (i.e. ``), serialize as an array (`{"foods": ["banana"]}`) instead of an object (`{"foods": {"0": "banana"}`). * **onBeforeParseValue: null**, if not null, allows you to prepare the value and return it by this method with signature `(value: string, type: string) => string;`. Also you may parametrize the serialization method: `.serializeForm(htmlFormElement, options, parsers)`. More info about options usage in the sections below. ## Custom Types ## You can define your own types or override the defaults with the `customTypes` option. For example: ```html
``` ```typescript NSerializeJson.parsers.push([ { name: "alwaysBoo", parse: (val: any, forceNull: boolean): any => { return "boo"; } } ]); var stringParser = NSerializeJson.parsers.filter(x => x.name === "string")[0]; stringParser.parse = (val: any, forceNull: boolean): any => { return val + " override"; } NSerializeJson.serializeForm(document.getElementById("myForm") as HTMLFormElement); // returns => { "scary": "boo", // <-- parsed with type :alwaysBoo "str": "str override", // <-- parsed with new type :string (instead of the default) "number": 5, // <-- the default :number still works } ``` The default parsers are defined in `NSerializeJson.parsers`. If you want to define your own set of parsers, you could also re-define that object. ## Use integer keys as array indexes ## By default, all serialized integer numbers are indices, so if you want to serialize it as string keys you have to set the `useNumKeysAsArrayIndex: false`: ```html
``` ```typescript NSerializeJson.options.useNumKeysAsArrayIndex = false; NSerializeJson.serializeForm(document.getElementById("myForm") as HTMLFormElement); // arr is an object => {'arr': {'0': 'foo', '1': 'var', '5': 'inn' }} NSerializeJson.options.useNumKeysAsArrayIndex = true; NSerializeJson.serializeForm(document.getElementById("myForm") as HTMLFormElement); // arr is an array => {'arr': ['foo', 'var', null, null, null, 'inn']} ```

npm version
npm downloads

Description

NSerializeJson is a Vanilla JS form serializer which serializes form data into JSON object.

Changes

v. 1.0.3 (2019-08-13)
  • Dot separator parsing fix.
  • Added more examples.
v. 1.0.2 (2018-11-11)

select element parsing fix.

Usage

Install

npm install nserializejson

Prepare and usage

Import:

  1. import {NSerializeJson} from "nserializejson";

or use the scripts tag (bundle):

  1. <script src="nserializejson.min.js"></script>

Define the HTML form:

  1. <form id="myForm">
  2. <input type="text" name="title" value="Finding Loot"/>
  3. <input type="text" name="author[name]" value="John Smith"/>
  4. <input type="text" name="author[job]" value="Legendary Pirate"/>
  5. </form>

Then:
(TypeScript)

  1. NSerializeJson.serializeForm(document.getElementById("myForm") as HTMLFormElement);

(JavaScript, using scripts tag)

  1. NSerializeJson.NSerializeJson.serializeForm(document.getElementById("myForm")); // In JS bundle NSerializeJson.* required, because of UMD library!

Returns:

  1. {
  2. title: "Finding Loot",
  3. author: {
  4. name: "John Smith",
  5. job: "Legendary Pirate"
  6. }
  7. }

Form input, textarea and select tags are supported. Nested attributes and arrays can be specified by using the attr[nested][nested] syntax.

HTML form:
```html