Reputation: 55
I have a newbie question with receiving JSON data from Python working as a server. I need to tell you that the server is based on WebSockets and I'm sending JSON data from Python to JavaScript successfully but I can't find any source how to proceed with this data to parse this and show it in different divs like value of the first_name
in the id="message-1"
div
, second_name
in the message2
div
etc. Could you help me figure this out? Here is the code and picture what my firefox return: Web page.
I almost forgot to mention that I'm using localhost with xampp or ngrok to "host" my client-side. Also, there is a connection because I'm receiving logs on the website as well as in python console
Thanks in advance :)
Here is python code:
import asyncio
import websockets
import json
async def time(websocket, path):
while True:
d = {'first_name': 'Guido',
'second_name': 'Rossum',
'titles': ['BDFL', 'Developer'],
}
parsed = json.dumps(d)
name = "Jeremy"
# now = datetime.datetime.utcnow().isoformat() + 'Z'
for i in range(1):
await websocket.send(parsed)
response = await websocket.recv()
print(response)
start_server = websockets.serve(time, '127.0.0.1', 4040)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Here is HTML/JS code
<body>
<div id="message-1"></div>
<div id="message-2"></div>
<div id="message-3"></div>
<script>
var ws = new WebSocket("ws://127.0.0.1:4040/");
ws.onopen = function () {
ws.send('Hello, Server!!');
//send a message to server once ws is opened.
console.log("It's working onopen log / awake");
};
ws.onmessage = function (event) {
if (typeof event.data === "string") {
// If the server has sent text data, then display it.
console.log("On message is working on log with onmessage :)");
var label = document.getElementById("message-1");
label.innerHTML = event.data;
}
};
ws.onerror = function (error) {
console.log('Error Logged: ' + error); //log errors
};
</script>
</body>
Upvotes: 1
Views: 6041
Reputation: 1497
ws.onmessage = function (event) {
try {
var obj = JSON.parse(event.data);
document.getElementById("message-1").innerHTML = obj.first_name;
document.getElementById("message-2").innerHTML = obj.second_name;
document.getElementById("message-3").innerHTML = obj.titles.join(" ");
} catch {
console.log("Object is not received, Message is:: ", event.data);
}
}
Remember JSON Needs to be valid json, Replace
'
(single-quote) with"
(double-quote):
d = {
"first_name": "Guido",
"second_name": "Rossum",
"titles": ["BDFL", "Developer"]
}
Upvotes: 2