Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 218
JN_newbie Avatar asked Aug 01 '16 16:08

JN_newbie


People also ask

Why is my JSON data 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.

Why is object property undefined JavaScript?

The JavaScript warning "reference to undefined property" occurs when a script attempted to access an object property which doesn't exist.

How to convert JavaScript object to JSON?

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.


1 Answers

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);
like image 153
Yogesh Rastogi Avatar answered Sep 28 '22 14:09

Yogesh Rastogi