Marty Balandis Marty Balandis - 1 month ago 8
JSON Question

Node.js / / Mysql to print as JSON

SOLVED: Answer is:
socket.on('clients', function(data)
{ document.write(JSON.stringify(data));

I want to get ouput like this (only the part in bold) on the screen as JSON:

debug - websocket writing 5:::{"name":"clients","args":[[{"id":6,"name":"demo

I must be missing something cause I just can't understand why it doesn't print as JSON. I have 3 files:

app.js (server) :

var fs = require('fs');
var db = require("./db.js");

var http = require('http').createServer(function handler(req, res) {
fs.readFile(__dirname + '/index.html', function (err, data) {
if (err) {
return res.end('Error loading index.html');
} else {
// -----------------------------------
var io = require('').listen(http);
io.sockets.on('connection', function (client) {
console.log('Client connected');
db.get_employees(function (employees) {
io.sockets.emit('clients', employees);

db.js (connect to database) :

// -----------------------------------
var mysql = require('mysql');
var client = mysql.createConnection({
user: 'xxxx',
password: 'yyyy',
host: '',
database: 'zzzz'
// -----------------------------------
exports.get_employees = function (callback) {
client.query("select id, name from clients", function (err, results, fields) {

And index.html :

<script src=""></script>
<script src=""></script>

$(document).ready(function() {
var socket = io.connect('');
socket.on('clients', function(data) {
$.each(data, function(i, obj) {
// document.write(obj); // Gets me [object Object][object Object]
// document.write( // Gets me name column
// document.write( // Gets me email column
// document.write(obj.xxxxx) // Gets me xxxxx column
// document.write(JSON.stringify(obj)); //Prints as JSON but structure is wrong and it is a html string not as JSON output


I am having trouble figuring why I cannot print it as JSON. See index.html commented lines. As well I want it to be a clean JSON output of my database and not as html.

The io.sockets.emit('clients', employees); in the App.js emits a correct json format I want but I can't get it outputted.I get [Object Object] or Undefined. There must be a way to do it because if I have to structure it manually it would make it speed inefficient.

Any help would be appreciated.

Answer Source

It's because you're outputting each JSON object on it's own. Try doing stringify on the "data" variable e.g.

$(document).ready(function() {
  var socket  = io.connect('');
  socket.on('clients', function(data) {