Maybe it is an easy topic, but I am trying and trying and I am not able to do this. I want to convert a string to a javascript object. Since now I tried multiple forms to resolve it. I am working with node and I want to make an AJAX request and the server side must to take the request variables and transform onto a javascript object (to make a extend with othe object). I show you how my code is:
var data = '{"addresses":"hola"}';
// make more and more.
makeTheRequest("POST",'users/update',"param="+JSON.stringify(data),'json',onSuccess, onError);
var param = eval('{' + req.body.param + '}');
console.log("\nuser.js-> router.post-> eval: " + param);
console.log("\nuser.js-> router.post-> req.param: " + req.body.param);
console.log("\nuser.js-> router.post-> JSON.parse: " + JSON.parse(req.body.param));
console.log("\nuser.js-> router.post-> user: " + req.session.user);
/*TODO: save on the database.... and more*/
res.send({success:0, error:1, result:"No USER. No SESSION"});
user.js-> router.post-> eval: {"addresses":"hola"}
user.js-> router.post-> req.param: "{\"addresses\":\"hola\"}"
user.js-> router.post-> JSON.parse: {"addresses":"hola"}
user.js-> router.post-> user: [object Object]
What I am trying to do is call the exentd function to merge the two objects, something like: req.session.user = extend(false, req.session.user, param);, but the param is handle like an array letter by letter-> 1:{, 2:", 3:a, 4:d, 5:d, 6:r, 7:e, 8:s, 9:s... Any idea what I am doing wrong?? Thank you very much.
You are encoding your data as JSON twice (in your example, data
is a string containing JSON), therefore your have to parse twice. The better solution would be to only encode it once and parse it once.
The fact that
console.log("\nuser.js-> router.post-> JSON.parse: " + JSON.parse(req.body.param));
produces
user.js-> router.post-> JSON.parse: {"addresses":"hola"}
tells you that the return value of JSON.parse
is still a string (containing JSON), not an object.