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.
The JSON-unsafe values on the other hand return : undefined if they are passed as values to the method. null if they are passed as an array element. nothing if passed as properties on an object.
The JavaScript warning "reference to undefined property" occurs when a script attempted to access an object property which doesn't exist.
The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With