HTML form JSON serializer on Vanilla JS
npm install nserializejson

select element parsing fix.
npm install nserializejson
typescript
import {NSerializeJson} from "nserializejson";
`
or use the scripts tag (bundle):
`html
`
Define the HTML form:
`html
`
Then:
(TypeScript)
`typescript
NSerializeJson.serializeForm(document.getElementById("myForm") as HTMLFormElement);
`
(JavaScript, using scripts tag)
`javascript
NSerializeJson.NSerializeJson.serializeForm(document.getElementById("myForm")); // In JS bundle NSerializeJson.* required, because of UMD library!
`
Returns:
`javascript
{
title: "Finding Loot",
author: {
name: "John Smith",
job: "Legendary Pirate"
}
}
`
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
`
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).
* 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']}
``