Reputation: 681
I have a simple Python tornado Websockets server, receives messages from JavaScript client. I am trying to send JSON data, the only solution I found is to convert the Json object into string Json, send it, on the other hand over the server I parse the string back to Json. Here is my Json file :
{
"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"
}
}
]
}
Before I send it I add another element to the 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;
}
I could receive the message from the server and print it:
So far good. but when I try to parse back to Json like this
JsonFormattedMessage = json.loads(message)[0]
I got this error:
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
Upvotes: 0
Views: 12828
Reputation: 834
I think the message is not a list, but the JSON String itself. So you are trying to access an index on a string, that does no exist. Try just loading the string in the json.loads function: json.loads(message)
Upvotes: 3