I'm turning a string into an object, then looping over that object. For some reason, if the string is semi-correctly formatted and I don't do the first two steps (replacing the parentheses with curly brackets) it works fine.
However, the replacement puts single ' instead of " (although it still parses without error). The parse misses putting the second id underneath the employeeType, and mistakenly puts it under employee.
https://codepen.io/MrMooCats/pen/zwpQGa
var str = "(id,created,employee(id,firstname,employeeType(id),lastname),location)";
str = str.replace(/[(]/g, "{"); // Possible problem line?
str = str.replace(/[)]/g, "}"); // Possible problem line?
str = str.replace(/([A-z])\s*{/g, "$1\":{");
str = str.replace(/([A-z])\s*([},])/g, "$1\":null$2");
str = str.replace(/({)/g, "{\"");
str = str.replace(/(,)/g, ",\"");
var objectStr = JSON.parse(str); // Object created, but wrong
var objectOutput = function(obj, counter) {
for(var i in obj) {
console.log(Array(counter+1).join("-") + " " + i);
if(obj.hasOwnProperty(i)){
if (obj[i] != null) {
objectOutput(obj[i], counter+1);
} else {
counter = 0;
}
}
}
};
objectOutput(objectStr, 0);
Actual output:
" id"
" created"
" employee"
"- id"
" firstname"
" employeeType"
"- id"
" lastname"
" location"
Expected Output
" id"
" created"
" employee"
"- id"
"- firstname"
"- lastname"
"- employeeType"
"-- id"
" location"
// Works fine if the ( are { instead and remove the first two lines- that's unreadable, can you just show what works?idis underemployee.