Traversing JSON object
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 开发者_JAVA技巧people is undefined. I know the data being sent is valid. How do I get my function to understand its dealing with JSON?
You can do
socket.json.send({data:'pepew'})
On the server side to send json, it will automatically be decoded by socket.io. And if you want to send json to the server you can simply do
socket.json.send({data:'boom'});
:D same api
If your data
is coming back as a JSON string, then you probably need to parse it as JSON first. This can be done using the $.parseJSON
method like so:
socket.on('message',function(data) {
var myData = $.parseJSON(data);
// the remainder of your code
});
You can find more information on $.parseJSON
in the JQuery documentation. Also worth noting is that if the browser that your code is running in has a native implementation of JSON.parse
, the $.parseJSON
method will use it.
You have to parse the JSON data first:
json = JSON.parse(data);
json.people[0].name;
or at least use:
json = eval('(' + data + ')');
精彩评论