I created a custom parseJSON function that is intended to produce the same result as JSON.parse when given the same input. There's also a helper function named getParsed() that correctly parses strings into their respective data types. However, I've encountered an issue:
parseJSON('{"boolean, true": true, "boolean, false": false, "null": null }')
// currently outputs {boolean, true: true, boolean, false: false, null: undefined}
What I actually need is for the last property to be returned as
null: null
to align with the output of JSON.parse()
I suspect there is some detail about null that I might be overlooking here, but I haven't been able to resolve this issue. Please find the code snippet below (at the moment, the function only handles object literals).
var getParsed = str => {
// Check if string is a number (floating point or integer)
if (/^-?\d*\.?\d+$/.test(str)) {
if (str.includes('.')) {
return parseFloat(str);
} else {
return parseInt(str);
}
}
// Check if string is enclosed in quotes (will remain as a string)
if (/"[^"]*()[^"]*"/.test(str)) {
var arr = str.split('');
arr.pop();
arr.shift();
return arr.join('');
}
// Check if string represents a boolean value
if (str === 'true') { return true; }
if (str === 'false') { return false; }
// Check if string is null or undefined
if (str === 'null' || str === 'undefined') { return null; }
};
var parseJSON = function (json, invoked = false) {
if (json.startsWith('{')) {
var arr = json.split('');
var first = arr.shift();
var last = arr.pop();
var props = arr.join('').split(', ');
var res = {};
for (var i = 0; i < props.length; i++) {
if (!props[i].includes(':')) {
props[i] = props[i] + ', ' + props[i + 1];
props.splice(i + 1, 1);
}
}
for (var i = 0; i < props.length; i++) {
var prop = props[i].split(': ');
var key = prop[0];
var val = prop[1];
if (key.includes('"')) {
key = key.split('');
key.shift();
key.pop();
key = key.join('');
res[key] = getParsed(val);
}
}
return res;
};