使用时,我无法JSON
在Node.js
服务器的客户端处理对象socket.io
。
这就是我发送数据的方式(我正在读取的文件具有JSON格式):
io.on('connection', function(socket){
console.log("A user connected");
fs.readFile('/.../file.json', 'utf-8', function(err, data){
socket.emit('news', JSON.stringify(data));
});
socket.on('disconnect', function(){
console.log("A user disconnected");
});
});
我打电话JSON.stringify
给二进制文件以可读的格式data
。
现在,在客户端,我<script>
在html的内部有以下代码块<body>
:
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io();
socket.on('news', function(data){
var obj= JSON.parse(data);
$("#json").text(obj);
});
</script>
运行得很好,我有一个段落<p id="json"></p>
占用了整个文本块,但是如果我尝试访问已解析的JSON元素并进行打印,例如使用console.log(obj.timestamp)
get ,则将其打印出来,例如“ timestamp”标签undefined
。
如何处理接收到的数据,以便将其作为常规JSON处理?
编辑
这是输出console.log(obj)
:
{
"timestamp": "Wed Aug 27 13:14:01 CEST 2014",
"devices": [
{
"A": {
"mac": "00:07:80:68:18:41",
"handles": [
{
"TxHandler1": "0418",
"TxHandler2": "020f00072a",
"TxHandler3": "bd",
"a": {
"hnd": "0x0010",
"uuid": "00002800-0000-1000-8000-00805f9b34fb",
"value": "0a 18 "
},
"b": {
"hnd": "0x0011",
"uuid": "00002803-0000-1000-8000-00805f9b34fb",
"value": "02 12 00 29 2a "
},
"c": {
"hnd": "0x0012",
"uuid": "00002a29-0000-1000-8000-00805f9b34fb",
"value": "56 4c "
},
"d": {
"hnd": "0x0013",
"uuid": "00002901-0000-1000-8000-00805f9b34fb",
"value": "46 41 "
},
"e": {
"hnd": "0x0014",
"uuid": "00002803-0000-1000-8000-00805f9b34fb",
"value": "02 15 00 24 2a "
},
"f": {
"hnd": "0x0015",
"uuid": "00002a24-0000-1000-8000-00805f9b34fb",
"value": "31 31 "
},
"g": {
"hnd": "0x0016",
"uuid": "00002901-0000-1000-8000-00805f9b34fb",
"value": "4d 4f 44 "
}
}
]
}
},
{
"B": {
"mac": "00:07:80:68:18:8E",
"handles": [
{
"TxHandler1": "0418",
"TxHandler2": "020f00072a",
"TxHandler3": "bd",
"a": {
"hnd": "0x0010",
"uuid": "00002800-0000-1000-8000-00805f9b34fb",
"value": "0a 18 "
},
"b": {
"hnd": "0x0011",
"uuid": "00002803-0000-1000-8000-00805f9b34fb",
"value": "02 12 00 29 2a "
},
"c": {
"hnd": "0x0012",
"uuid": "00002a29-0000-1000-8000-00805f9b34fb",
"value": "56 4c "
},
"d": {
"hnd": "0x0013",
"uuid": "00002901-0000-1000-8000-00805f9b34fb",
"value": "46 41 "
},
"e": {
"hnd": "0x0014",
"uuid": "00002803-0000-1000-8000-00805f9b34fb",
"value": "02 15 00 24 2a "
},
"f": {
"hnd": "0x0015",
"uuid": "00002a24-0000-1000-8000-00805f9b34fb",
"value": "31 31 "
},
"g": {
"hnd": "0x0016",
"uuid": "00002901-0000-1000-8000-00805f9b34fb",
"value": "4d 4f 44 "
}
}
]
}
}
]
}
根据JSON Lint的说法,它是有效的json,但是undefined
当我尝试访问“时间戳”标签时仍然遇到问题
我发送了错误的数据格式,正确的代码是:
io.on('connection', function(socket){
console.log("A user connected");
fs.readFile('/.../file.json', 'utf-8', function(err, data){
socket.emit('news', data.toString());
});
socket.on('disconnect', function(){
console.log("A user disconnected");
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句