node.js - Error in parsing json array accepting multiple values -
whenever giving single data element in json file code works fine,but give array of elements starts showing undefined on client side. server side code.
var app = require('express')() , server = require('http').createserver(app) , io = require('socket.io').listen(server); var fs= require('fs'); server.listen(3000); app.get('/', function (req, res) { res.sendfile(__dirname + '/cli_index.html'); }); io.sockets.on('connection', function (socket) { var file = __dirname + '/data.json'; fs.readfile(file, 'utf8', function (err, data) { if (err) { console.log('error: ' + err); return; } data = json.parse(data); // can save values somewhere or log them console console.log(data); socket.emit('news', { hello: data}); }); });
this client side code.
<script src="/socket.io/socket.io.js"></script> <script> var socket = io.connect('http://localhost'); socket.on('news', function (data) { json.stringify(data); for(var i=0;i<2;i++){ document.write(data[i].hello.name); } }); </script>
this external json file.
[{"name":"hey"},{"name":"gouraw"}]
in server side code:
socket.emit('news', { hello: data});
...you're sending array hello
property of object, client-side code:
document.write(data[i].hello.name);
...is expecting top-level array, individual hello
properties each entry. change to:
document.write(data.hello[i].name);
...so you're indexing array.
it best, well, limit loop using array's length
rather hardcoded value:
for(var i=0;i<data.hello.length;i++){
Comments
Post a Comment