2016-11-15 131 views
0

我收到來自HTTP post作爲json對象數組的響應。但想顯示爲字符串。請參閱我的回覆..如何將json對象的數組轉換爲Nodejs中的String?

{ total: 14, 
    results: 
    [ { name: [Object], 
     comments: [], 
     attributes: [Object], 
     type: [Object], 
     context: [Object], 
     status: 'Accepted', 
     score: 1.7646775, 
     modified: 1426085315767, 
     parents: [] }, 
    { name: [Object], 
     comments: [], 
     attributes: [Object], 
     type: [Object], 
     context: [Object], 
     status: 'Accepted', 
     score: 1.3945999, 
     modified: 1425386916807, 
     parents: [] }, 

下面的代碼顯示響應。

function(error, response, data){ 
    if(error) { 
     console.log(error); 
    } else { 
      console.log(data); 

} 
+4

可你只需要使用'的console.log(JSON.stringify(數據))'? –

+0

你可以這樣做:'const arrAsStr = arr.map((r)=> JSON.stringify(r));' – Hosar

回答

2

擁有的NodeJS ES5 JSON類具有stringify()方法,它

function(error, response, data){ 
    if(error) { 
     console.log(error); 
    } else { 
     console.log(JSON.stringify(data)); 
} 

JSON.stringify

+0

很好。它的工作..如何從json獲取特定的字段值? – user2848031

+0

'JSON.stringify()'將接受任何javascript對象並將其轉換爲json字符串。所以它訪問JSON字符串內的屬性,你必須將它解析回js對象。你可以使用'JSON.parse(「json string goes here」)來做到這一點 –

相關問題