JavaScript - 为什么json stringify不起作用?

时间:2016-03-21 08:50:43

标签: javascript json google-chrome google-chrome-extension

为什么jsonObject.msgundefined?即使我从{"msg":"not_inserted"}获得response.farewell的价值。

(仅供参考:response.farewell是Google Chrome应用生成的JSON值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);
  }

输出:

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

预期产出:

>>> not_inserted

1 个答案:

答案 0 :(得分:0)

尝试使用单引号将传递给sendMessage的字符串换行,删除额外的双引号

sendMessage('{\"msg\" : \"' + tmp + '\"}')