JSON.parse()解析json字符串之后value的值还是buffer类型?
发布于 7 年前 作者 xuxiaoyu9510 4083 次浏览 来自 问答

ws.on(‘connection’, function connection(socket) { socket.on(‘message’, function (message) { console.log(message) let test = JSON.stringify(message) let msg = JSON.parse(test) console.log(msg) }) })

输出msg:

{ type: ‘Buffer’, data: [ 123, 34, 108, 34, 100, 111, 110, 103, 102, 104, 109, 34, 57, … 11 more items ] }

3 回复

message是Buffer对象,为什么要用JSON.stringify转换?得到完整的Buffer后使用toString()就行了吧

另外你有两条console.log,确定输出的这个是msg而不是message吗

SyntaxError: Unexpected token d in JSON at position 0,如果用toString()会出现前边这种错误。确定不是,因为我并没有把结果全部贴出来,如果是message的话,是这个结果<Buffer 7b 22 74 79 70 65 22 3a 22 6d 61 63 68 69 6e 65 22 2c 22 70 61 79 6c 6f 61 64 22 3a 7b 22 6d 61 63 68 69 6e 65 62 72 61 6e 64 22 3a 22 64 6f 6e 67 66 ... >

可能有两个原因:第一,你的ws数据流过大被截断了,所以没有办法toString;第二,传过来的数据格式非法;

回到顶部