Reputation: 5651
My string is not formatted correctly, using JavaScript, let's say the data is:
{engine{type{condition},age},wheels,model{name},color}
And I want to convert that to a usable (JS) object. I could use regex to parse out pieces, but I'm wondering if there's a non-regex method to do so. If you had to do it in regex, what would be the easiest way of doing it?
Converted object should be something more like:
{
engine: {
type: {
condition: null
},
age: null
},
wheels: null,
model: {
name: null
},
color: null
}
I could also work with it from a series of nested arrays.
Upvotes: 1
Views: 63
Reputation: 8833
Well, under the assumption that that "char{" should be "char:{" and "char," or"char}" should be "char=null," or "char=null}", this is a pretty simple find and replace. Otherwise, you might have to use a recursive parse function to rip it apart and put it back together again.
var str = "{engine{type{condition},age},wheels,model{name},color}"
str = str.replace(/([A-z])\s*{/g, "$1:{")
str = str.replace(/([A-z])\s*([},])/g, "$1:null$2")
console.log(str);
Upvotes: 1