JN_newbie JN_newbie - 1 year ago 66
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 Source

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);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download