JN_newbie JN_newbie - 4 months ago 9
JSON Question

cannot access json object property returns undefined

I am accessing a key from json object but it returns undefined

{"body":"Hi","date":"2016-07-29 07:43:00"}

var a = JSON.parse(JSON.stringify(r.txt));
console.log(a.body)

//undefined


value of r is

{
username: '1',
txt: '{"body":"Hi","date":"2016-07-29 07:43:00"}',
}


I have tried using stringify and then parse to json but still return undefined.

Answer

You've to parse your json like this. Ensure that your whatever input you're giving to JSON.parse, it should be a string.

You can run the below snippet to ensure that it's working and giving output Hi.

var json = '{"body":"Hi","date":"2016-07-29 07:43:00"}';

var a = JSON.parse(json);
document.write(a.body);