I have the following code in an HTML file:
socket.on('message',function(data) {
console.log('Received a message from the server!',data);
$('#data').append('<br />'+data.toString('utf8'));
});
The server at certain points sends a string or sends a JSON object to the client however when I try to use JSON syntax to access the data eg/ $('#data').append(data.people[0].name]) it throws an error saying people is undefined. I know the data being sent is valid. How do I get my function to understand its dealing with JSON?
If your
datais coming back as a JSON string, then you probably need to parse it as JSON first. This can be done using the$.parseJSONmethod like so:You can find more information on
$.parseJSONin the JQuery documentation. Also worth noting is that if the browser that your code is running in has a native implementation ofJSON.parse, the$.parseJSONmethod will use it.