S G
S G

Reputation: 25

nodejs object.property undefined error on parsing json

I am using nodejs 0.10.32/33 but with either of them i am getting undefined exception on accessing the property of a json object. My test class looks like below:

var jvar = '{"name":"sumit","age":"33"}';
var stdata = JSON.stringify(jvar);
var sdata = JSON.parse(stdata);
console.log(sdata);
console.log(sdata.name);

and output from the above code is:

{"name":"sumit","age":"33"}
undefined

I am unable to get what I am missing here.

Upvotes: 1

Views: 4826

Answers (2)

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

you need to parse the string as JSON, because its already string, so no need to use JSON.stringify(), use only JSON.parse instead, as:

var jvar = '{"name":"sumit","age":"33"}';
var stdata = JSON.parse(jvar);

console.log( stdata.name ); //gives sumit

Upvotes: 3

ariel_556
ariel_556

Reputation: 378

stringify is to convert a json object to string. not vice versa.

var jvar = {"name":"sumit","age":"33"};
var stdata = JSON.stringify(jvar);
var sdata = JSON.parse(stdata);
console.log(sdata);
console.log(sdata.name);

Upvotes: 0

Related Questions