5

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.

4
  • 2
    share value of r Commented Aug 1, 2016 at 16:54
  • if r is the object remove .txt and it will work jsfiddle.net/z_acharki/jnwrc5ay/158 Commented Aug 1, 2016 at 16:55
  • @PranavCBalan, I have shared the value Commented Aug 1, 2016 at 16:59
  • 2
    @JN_newbie var a = JSON.parse(r.txt); , it's already a json string no need to stringify it Commented Aug 1, 2016 at 17:00

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

Comments

3

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)

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.