简体   繁体   English

JSON.parse 意外令牌节点

[英]JSON.parse unexpected token NODE

Using client.on('data', function(data){}) A node socket passes in the following data:使用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"

} }

using JSON.parse(data) results in Uncaught SyntaxError: Unexpected token in JSON at position 201使用JSON.parse(data)导致Uncaught SyntaxError: Unexpected token in JSON at position 201

If I pass the string directly all works well.如果我直接传递字符串一切正常。

Thanks in advance.#提前致谢。#

EDIT1:编辑1:

My Code:我的代码:

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
});

It works if:它在以下情况下有效:

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:编辑2:

Electron environment connected to local socket server.电子环境连接到本地套接字服务器。 No control of servers output无法控制服务器输出

use this:用这个:

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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM