I am trying to convert quoted numbers (string) to automatic type by removing quotes from them via regex. Like from "123" to 123.
I am using JSON.parse reviver function but cant seem to replace it.
What I need:
- replace in reviver should work. See code below
- Generic correct regex which can handle all kind of numbers. I am not sure if i am using right regex.
- Is there any library already doing stuff like this ? Please mention
JSFIDDLE: https://jsfiddle.net/bababalcksheep/j1drseny/
CODE:
var test = {
"int": 123,
"intString": "123",
"Scientific_1_String": "5.56789e+0",
"Scientific_1": 5.56789e+0,
"Scientific_2_String": "5.56789e-0",
"Scientific_2": 5.56789e-0,
"Scientific_3_String": "3.125e7",
"Scientific_3": 3.125e7,
"notNumber": "675.805.714",
"dg": "675-805-714",
"hex": "675.805.714",
"trueString": "true",
"trueBool": true,
"falseString": "false",
"falseBool": false,
};
test = JSON.stringify(test);
var parsedJson = JSON.parse(test, function(key, value) {
if (typeof value === 'string') {
if (value === 'false') {
return false;
} else if (value === 'true') {
return true;
} else {
// try to remove quotes from number types
value = value.replace(/"(-?[\d]+\.?[\d]+)"/g, "$1");
return value;
}
} else {
return value;
}
});
console.log(parsedJson);