JSON.parse意外令牌NODE

时间:2017-10-26 09:33:38

标签: javascript json node.js

使用client.on('data', function(data){})节点套接字传入以下数据:

{
 "jsonrpc": "2.0",
 "result": {
           "Name": "MyGain",
           "Controls": [
                        {
                         "Name": "gain",
                         "String": "-18.0dB",
                         "Value": -18,
                         "Position": 0.68333333
                        },
                        {
                         "Name": "mute",
                         "String": "unmuted",
                         "Value": 0,
                         "Position": 0
                        }
                       ]
            },
 "id": "upd"

}

使用JSON.parse(data)会产生Uncaught SyntaxError: Unexpected token in JSON at position 201

如果我直接传递字符串一切正常。

提前致谢。#

EDIT1:

我的代码:

this.client = new net.Socket();
this.client.setEncoding('utf8');
this.client.on('data', function(data) {
console.log('raw:' + data);
var dataj = JSON.parse(data);
// console.log(b);
if (dataj.id == "upd") {
    console.log("UPDATE MESSAGE");
} else {
    console.log('unknown:' + data);
}
// client.destroy(); // kill client after server's response
});

在以下情况下有效:

this.client = new net.Socket();
this.client.setEncoding('utf8');
this.client.on('data', function(data) {
console.log('raw:' + data);
var dataj = JSON.parse({"jsonrpc":"2.0","result":{"Name":"MyGain","Controls":[{"Name":"gain","String":"-65.0dB","Value":-65.0,"Position":0.29166665},{"Name":"mute","String":"unmuted","Value":0.0,"Position":0.0}]},"id":"upd"});
// console.log(b);
if (dataj.id == "upd") {
    console.log("UPDATE MESSAGE");
} else {
    console.log('unknown:' + data);
}
// client.destroy(); // kill client after server's response
});

EDIT2:

连接到本地套接字服务器的电子环境。无法控制服务器输出

1 个答案:

答案 0 :(得分:0)

使用它:

this.client = new net.Socket();
this.client.setEncoding('utf8');
this.client.on('data', function(data) {
console.log('raw:' + data);
var dataj = data
// console.log(b);
if (dataj.id == "upd") {
   console.log("UPDATE MESSAGE");
 } else {
  console.log('unknown:' + data);
 }
 // client.destroy(); // kill client after server's response
});