简体   繁体   中英

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.

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

In your code stringified result would be "\\"{\\"body\\":\\"Hi\\",\\"date\\":\\"2016-07-29 07:43:00\\"}\\"" (which is valid string representation in JSON), parsing it would again provide the string as result not the object. When you were trying to get body property of string which will be undefined since there is no property like body for a string.

So there is no need to stringify a JSON string again just avoiding the stringify method would make it work.

 var r = { username: '1', txt: '{"body":"Hi","date":"2016-07-29 07:43:00"}', }; // parse the JSON string and get the object var a = JSON.parse(r.txt); console.log(a.body) 

You have to remove single quote in r.txt and it should work

Here is the code I updated :

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

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

If r.txt is string you only need parse it. If it's an object , you will convert it to string by stringify then parse it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM