0

Why jsonObject.msg is undefined? even i am getting value as {"msg":"not_inserted"} from response.farewell.

( FYI: where response.farewell is Google chrome apps generated JSON value sendMessage("{\"msg\" : \"" + tmp + "\"}"); )

//var reply ='{"msg":"not_inserted"}';
//var jsonstring = JSON.parse(reply);
//console.log('>>> ' , jsonstring.msg); // it WORKS!


try {
    console.log("REPLY: ", response.farewell); 

    // it FAILS!!
    var jsonString = JSON.stringify(response.farewell);        
    var jsonObject = JSON.parse(jsonString);        
    console.log('>>> ' , jsonObject.msg);

  } catch(eio) {        
    console.log(eio);
  }

Output:

REPLY: {"msg":"not_inserted"}
>>> undefined 

Expected output:

>>> not_inserted

12
  • 1
    Have you tried response.farewell.msg? without using JSON.stringify or JSON.parse? Commented Mar 21, 2016 at 8:54
  • 1
    Is tmp a variable ? Commented Mar 21, 2016 at 8:57
  • 1
    What is response.farewell initially? Commented Mar 21, 2016 at 8:58
  • 1
    Are you including extra quotes " at \"" + tmp + "\" ? Commented Mar 21, 2016 at 9:00
  • 1
    response.farewell doesn't seem to be an object... I get "REPLY: Object {msg: "not_inserted"}" on my side if I use response = { farewell: { "msg": "not_inserted" } } Commented Mar 21, 2016 at 9:08

1 Answer 1

1

Try using single quotes to wrap string passed to sendMessage, removing extra double quotes

sendMessage('{\"msg\" : \"' + tmp + '\"}')
Sign up to request clarification or add additional context in comments.

4 Comments

i.imgur.com/fdLUl3X.png - when i trying to apply your were in Java, its syntax error.
@YumYumYum The images are not reproducible. If possible can you create a stacksnippets or jsfiddle to demonstrate ? See jsfiddle.net/t2opa459/2
Thanks it works. so my tmp was broken i fixed it like you said.
Down-vote was not by me, someone else did i have still +1 there with accepted answer. thank you.

Your Answer

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