我有一个简单的Python龙卷风Websockets服务器,从JavaScript客户端接收消息。我试图发送JSON数据,我找到的唯一解决方案是将Json对象转换为字符串Json,发送它,另一方面通过服务器将字符串解析回Json。这是我的Json文件:
{
"events": [
{
"id": 0,
"new": {
"description": "blabla bla keyyys",
"keys": [
"keyyys",
"key "
],
"start": "2.000000",
"end": "7.000000",
"priority": "normal"
}
},
{
"id": 1,
"new": {
"description": "anything key ",
"keys": [
"keyyys",
"key "
],
"start": "0.761077",
"end": "10.026667",
"priority": "high"
}
}
]
}
在发送之前,我向Json添加了另一个元素:
var messageValue = {};
var sendings;
messageValue["messageType"] = "mainfest";
$.getJSON("file.json", function(json) {
messageValue["data"]= json;
console.log(messageValue);
sendings = jsonToStringConvertor(messageValue);
});
var socket = new WebSocket('ws://localhost:9000/');
socket.onopen = function(event){
socket.send(sendings);
}
。
function jsonToStringConvertor(obj)
{
var re = JSON.stringify(obj);
return re;
}
到目前为止还不错。但是当我尝试像这样解析Json时
JsonFormattedMessage = json.loads(message)[0]
我收到了这个错误:
ERROR:tornado.application:Uncaught exception in /
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/tornado/websocket.py", line 494, in _run_callback
result = callback(*args, **kwargs)
File "index.py", line 27, in on_message
JsonFormattedMessage = json.loads(message)[0]
KeyError: 0
答案 0 :(得分:2)
我认为该消息不是列表,而是JSON字符串本身。所以你试图访问一个不存在的字符串索引。尝试在json.loads函数中加载字符串:json.loads(message)