Rafael Motta
Rafael Motta

Reputation: 2527

Transform object to JSON

I have an object like this:

{  
  user[id]: 1,  
  user[name]: 'Lorem',  
  money: '15.00'  
}

And I want this:

{  
  user: {  
    id: 1,  
    name: 'Lorem',  
  },  
  money: '15.00'  
}

How can I achieve this?

Upvotes: 0

Views: 95

Answers (1)

Musa
Musa

Reputation: 97672

Something like this

var x = {  
  "user[id]": 1,  
  "user[name]": 'Lorem',  
  "money": '15.00'  
}
var y = {};
for (var i in x){
    var  z = /(.+)\[(.+)\]/g.exec(i);
    if (z){
        if (!y.hasOwnProperty(z[1])){
            y[z[1]] = {};
        }
        y[z[1]][z[2]] = x[i];   
    }
    else{
        y[i] = x[i];
    }
}

http://jsfiddle.net/mowglisanu/3Z2qe/

Upvotes: 2

Related Questions