我正在为一个应用程序的node.js API工作,该应用程序具有接受NDJSON的简单TCP服务器(基本上由'\ r \ n'分隔)。无论如何,我遇到了JSON stringify的问题。我用变量创建一个对象(见下文),然后将其转换为stringify。当我得到结果时,它扩展了除“requestParamName”之外的所有变量。这是唯一的关键,而不是价值,这就是结果:
{"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);
}
P.S。我是新来的,所以如果我弄乱格式化,我道歉;)
答案 0 :(得分: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;
答案 1 :(得分:0)
[变量]是你需要的,否则它将与上面的^^
相同