Reputation: 855
I am sending the string from AngularJS to NodeJS in following form.
"{↵obj:{↵one:string,↵two:integer↵}↵}"//request object from browser console
I want to convert this string in object and use its properties.for this the server side code is following:
var data=req.body.data.replace(/"/g,"");
var str=data.replace(/\n/g," ");
//res.json(str) // returning "{ obj:{ one:string, two:integer } }"
try {
var obj=JSON.parse(JSON.stringify(str)).replace(/"/g,"");
res.json(obj);//returning same "{ obj:{ one:string, two:integer } }"
} catch (error) {
console.log(error);
}
I want to get ['users'] by Object.keys[obj] or by any other method want to access the properties of this object.but failed to achieve this.
Many solutions like This couldn't be helpful.any suggestion here??
Upvotes: 1
Views: 10363
Reputation: 1478
For example my raw data is like this :
var raw_data =
{
"ok": true,
"user": {
"id": "U89MZ4PV2",
"team_id": "T895HCY8H",
"name": "hyosoka187",
}
}
then just use JSON.parse(raw_data, true);
. So
var real_data = JSON.parse(raw_data, true);
console.log(real_data.user.name);
Result :
hyosoka187
NOTE :
Output of JSON.parse(raw_data, true) :
{
ok: true,
user: {
id: 'U89MZ4PV2',
team_id: 'T895HCY8H',
name: 'hyosoka187',
}
}
Upvotes: 0
Reputation: 740
All you need is JSON.parse
to convert string to object.
Something like this:
var jsonString='{"obj":{"one":"string","two":"integer"}}';
console.log(JSON.parse(jsonString));
Output:
{ obj: { one: 'string', two: 'integer' } }
Upvotes: 2