2016-02-29 121 views
-2

我有一個來自一個HTTP請求以下JSON字符串:JSON解析對象

{ '{firstname:\'Joe\'}': '' } // output of console.log(req.body); 

我試圖打印的價值利用到控制檯:

console.log(req.body.firstname); 

,但它說,該值未定義。我怎樣才能得到名字的價值?

要了解客戶是這樣做的是如何發送JSON請求:

//angular2 
headers.append('Content-Type', 'application/x-www-form-urlencoded'); 
     this.http.post(
      'http://192.168.1.45:3000/test', 
      JSON.stringify({firstname:'Joe'}), //This is the parameter I want 
      {headers:headers} 
     ) 
+0

它似乎沒有驗證JSON –

+0

'{firstname:\'Joe \'}'是對象的'key' .. – Rayon

+0

您顯示的對象已被解析爲JavaScript對象或者它是無效的JSON串。除此之外,':'之前的部分是鍵(所以你的鍵是'{firstname:\'Joe''')。它表明答覆已經是錯誤的,或者你在做出錯誤的事情。 –

回答

0

通過透過JSON.stringify轉換數組JSON字符串,然後將字符串轉換回數組使用JSON.parse

<html> 
    <head> 
    <script> 
    function gettz(){ 
    var str=JSON.stringify({firstname:'Joe'}); 
    console.log(str); 
    //Parse an object 
    dataObj = JSON.parse(str); 
    // get object property 
     console.log(dataObj.firstname); 
    } 

    </script> 
    </head> 
    <body> 
     <input type="button" id="button" value="PrintJson" onclick="gettz();"> 
    </body> 
    </html> 
+0

爲什麼OP應該從JavaScript對象中創建JSON字符串,然後將其轉換回下一行中的JavaScript對象?爲什麼不寫'dataObj ='{firstname:'Joe'}';'? –

+0

如果@ user2924127想要使用解析json訪問對象屬性。類似於OOP概念。 –

+0

當你在標題中發送它時,它已經是字符串格式,你需要解析它。在你可以訪問它之後。 –

0

當你收到它,你需要先解析響應,因爲它作爲一個字符串來了,所以做:

var parsedResponse = JSON.parse(req.body); 
console.log(parsedResponse.firstname); //Now you can access the object 
+0

如果'{'{firstname:\'Joe \'}':''}'實際上是'console.log(req.body);'的輸出,那麼'JSON.parse'會導致'Uncaught SyntaxError :意外的標記'',因爲對於JSON,鍵必須用雙引號括起來。 –