I am trying to parse this string into a organized set of functions:
var str = "a(b, c(e, f(h,i,j), g(k,l,m(o,p,q)) ), d(r,s,t))"
Ideally I would like to turn it into an object like this:
var obj = {
func:'a',
params:[
{p:'b'},
{p: {
func:'c',
params:[
{
p:'e',
p:{
func:'f',
params:[
{p:'h'},
{p:'i'},
{p:'j'}
]
},
p:'g',
params:[
{p:'k'},
{p:'l'},
{p:{
func:'m',
params:[
{p:'o'},
{p:'p'},
{p:'q'}
]
}}
]
}
]
}},
{
p:'d',
params:[
{p:'r'},
{p:'s'},
{p:'t'}
]
}
]
}
I have tried about 8 hours of mixed str.replace() str.substring(), and str.indexOf() and not had any luck.
Any help about how to go about achieving my goal would be appreocated.
note: the functions could take any number params and is not set to 3
UPDATE -- I stopped trying to do string manipulation and approached it character by character. To create desired output:
var str = "a(b, c(e, f(h,i,j), g(k,l,m(o,p,q)) ), d(r,s,t))";
str = str.replace('/ /g,""');
var strArr = str.split('');
var firstPass = "";
var final;
var buildObj = function(){
for(var i = 0; i < strArr.length; i++){
var letters = /^[0-9a-zA-Z]+$/;
if(strArr[i].match(letters)){
if(strArr[i + 1] == '('){
firstPass += '},{"func":' + '"' + strArr[i] + '"';
} else {
firstPass += '"' + strArr[i] + '"';
}
}
if(strArr[i] == '('){
firstPass += ',"params":[{"p":';
}
if(strArr[i] == ')'){
firstPass += '}],';
}
if(strArr[i] == ','){
firstPass += '},{"p":';
}
//console.log(job + '}')
}
var secondPass = firstPass;
secondPass += '}'
secondPass = secondPass.replace(/,{"p":}/g,'');
secondPass = secondPass.replace('},','');
secondPass = secondPass.replace(/],}/g,']}');
final = secondPass
console.log(final)
console.log(JSON.parse(final))
};