I've got code that takes form fields and converts them into a JSON string suitable for passing to a REST API (the marathon REST API specifically). The problem is that JSON.stringify double quotes all the form field values, even those that are numeric, which causes the ajax call to fail. Here's the string my code is producing:
{"id":"basic-1","cpus":"0","mem":"32","instances":"1","cmd":"while [ true ] ; do echo 'Hello Marathon' ; sleep 5 ; done"}
The mem, cpus, and instances values should not be double quoted because they're numeric.
data: JSON.stringify($('form').MytoJson());
MytoJson is a function that serializes the form fields. That's working fine. The problem is that JSON.stringify is putting the quotes around the keys and all the values, including the numeric values, which is causing the ajax call to fail.
The JSON.stringify function takes two arguments. The first argument is a replacer function, which can be a function or an array. Consider this replacer function:
function replacer(key, value) {
if (typeof value === "string") {
return undefined;
}
return value;
}
JSON.stringify($('form').MytoJson(), replacer);
I want to modify this replacer function to not quote numeric values. I'm wondering if I have use the HTML5 form attributes to differentiate between string and numeric form fields? Consider this form field:
<input id="cpus" type="number" name="cpus" value="0.1" />
How can I use the fact that this field has the attribute type="number" in the replacer function? I want to modify the replacer function to not quote values when the form field is of type number.