joyent/node — Issue #1908: JSON.stringify returning invalid json
Author: victorjonsson
Created: 2011-10-18 18:45:42+00:00
State: open

I have just begun with my first node project so pls forgive me if this is a mistake on my part.

For some reason the string returned by JSON.stringify is missing the last brace and I can't see that this is something else then a bug.

```javascript

/* Namespace... */
var ProjectX = {};

/**
* Lorem te ipsum...
* @class ProjectX.API
*/
ProjectX.API = function() {

/**
* @return {ProjectX.API.AbstractResponse}
*/
this.dispatchRequest = function(method, path) {
//throw new Error('Not implemented yet...');

var que = {
id : 1294482,
question : "Vad är 1+1",
answers : [2, 3, 99, 'What ever'],
img : {
id : 3298923,
url : "http://google.se"
}
};

return new ProjectX.API.AbstractResponse(que, 200);
};

/**
* @return {ProjectX.API.AbstractResponse}
*/
this.generateErrorResponse = function(errorMessage) {
return new ProjectX.API.AbstractResponse({message:errorMessage}, 500);
};
};

/**
* Object used as template when constructing an API responses
* @class ProjectX.API.AbstractResponse
*/
ProjectX.API.AbstractResponse = function(body, statusCode) {

this.statusCode = statusCode;
this.contentType = 'application/json';

// Private variables
var _jsonBody = false;
var _body = body;

this.setBody = function(body) {
_jsonBody = false;
_body = body;
};

this.getBody = function() {
return _body;
};

/**
* @return {Number}
*/
this.contentLength = function() {
return this.getBodyAsJSON().length;
};

/**
* @return {String}
*/
this.getBodyAsJSON = function() {
if(!_jsonBody) {
_jsonBody = JSON.stringify(_body);
}

return _jsonBody;
};
};

/* * * * * * * * * * * * * *
* Server setup
* * * * * * * * * * * * * * */
var http = require('http');
http.createServer(function (req, res) {

var api = new ProjectX.API();
var apiResponse;

try {
apiResponse = api.dispatchRequest('GET', '/');
}
catch(e) {
console.log(e.message);
apiResponse = api.generateErrorResponse(e.message);
}

res.statusCode = apiResponse.statusCode;
res.setHeader('Content-length', apiResponse.contentLength());
res.setHeader("Content-Type", apiResponse.contentType);
res.end(apiResponse.getBodyAsJSON());

}).listen(1337, "127.0.0.1");

console.log('Server running at http://127.0.0.1:1337/');