2017-02-22 172 views
1

我正在使用接受NDJSON的簡單TCP服務器(本質上由'\ r \ n'分隔)的應用程序的node.js API。無論如何,我遇到了JSON stringify的問題。我用變量創建一個對象(見下文),然後將其轉換爲stringify。當我得到結果時,它擴展了除「requestParamName」之外的所有變量。這是唯一的關鍵,而不是作爲一個價值,這是結果:Node.js JSON.stringify變量不擴展

{"jsonrpc":"2.0","method":"Client.SetVolume","id":0,"params":{"client":"00:00:00:00:00:00","requestParamName":10}} 

它應該是這樣的:

{"jsonrpc":"2.0","method":"Client.SetVolume","id":0,"params":{"client":"00:00:00:00:00:00","volume":10}} 

我已經試過幾件事情,但我不知道是什麼導致它不能擴展這個特定的變量。如果有人有任何建議,我會很感激。

功能:

function ClientConnect(requestMethod, requestMacAddress, requestParamName, requestParamKey) { 
    var objectRequest = { 
     "jsonrpc": "2.0", 
     "method": requestMethod, 
     "id": 0, 
     "params": { 
      "client": requestMacAddress, 
      requestParamName: requestParamKey 
     }}; 

    formattedJson = (JSON.stringify(objectRequest) + '\r\n'); 
    console.log(formattedJson); 
} 

附:我是新來的,所以如果我搞砸了格式化,我道歉;)

回答

0

其實這樣做:

"params": { 
     "client": requestMacAddress, 
     requestParamName: requestParamKey 
    }}; 

是完全一樣的是:

"params": { 
      "client": requestMacAddress, 
      "requestParamName": requestParamKey 
     }}; 

你要做這樣的(請注意,這是一個ES6的特點 - 如果你使用了最近的node.js它的確定):

var objectRequest = { 
     "jsonrpc": "2.0", 
     "method": requestMethod, 
     "id": 0, 
     "params": { 
      "client": requestMacAddress, 
      [requestParamName]: requestParamKey 
     }}; 

的ES5版本會:

var objectRequest = { 
     "jsonrpc": "2.0", 
     "method": requestMethod, 
     "id": 0, 
     "params": { 
      "client": requestMacAddress 
     }}; 
objectRequest[requestParamName]= requestParamKey; 
+0

以上哇,我不知道有這個東西括號沒有。它非常完美!萬分感謝! –

0

[變量]是你所需要的,否則會是一樣的^^

+0

請您詳細說明一下嗎? –