javascript - JSON stringify converts 0 to null -
i trying convert object json doesn't convert enum 0. when print enum 0 when use inside object becomes null. if use string, instead of integer works.
(function () { 'use strict'; var itemstatus = { 'prepared': 0, 'ongoing': 1, 'finished': 2 }; module.exports = itemstatus; })(); (function () { 'use strict'; var itemstatus = require('./itemstatus'); function itemdetail(detail) { detail = detail || {}; this.message = detail.message || null; this.location = detail.location || null; this.status = detail.status || null; this.date = detail.date || null; } module.exports = itemdetail; })(); (function () { 'use strict'; var itemdetail = require('./itemdetail'); var itemstatus = require('./itemstatus'); function item(item) { item = item || {} this.name = item.name || null; this.details = item.details || []; this.isfinished = item.isfinished || null; this.finishdate = item.finishdate || null; } item.prototype.adddetail = function(message, location,date,status) { if (this.isfinished) { this.isfinished = false; } console.log('status: ' + status); //prints 0 correctly var detail = new itemdetail({ message: message, location: location, date:date, status:status }); this.details.push(detail); if (status === itemstatus.finished) { this.isfinished = true; this.finishdate = date; } }; module.exports = item; })();
failing test
var should = require('should'); var item = require('../lib/models/item'); var itemdetail = require('../lib/models/itemdetail'); var itemstatus = require('../lib/models/itemstatus'); describe('item detail test:', function() { this.enabletimeouts(false); var myitem = new item({ name: 'something', }); myitem.adddetail('something happened','ny',1212122,itemstatus.prepared); myitem.adddetail('another thing','ny',1412122,itemstatus.ongoing); myitem.adddetail('it done','ny',1212122,itemstatus.finished); it('should print json', function() { myitem.name.should.eql('something'); console.log(myitem.details[0].status); myitem.details[0].status.should.eql(itemstatus.prepared); console.log(json.stringify(myitem)); }); });
when printed item shows following
{"name":"something","details":[{"message":"something happened","location":"ny","status":null,"date":1212122},{"message":"another thing","location":"ny","status":1,"date":1412122},{"message":"it done","location":"ny","status":2,"date":1212122}],"isfinished":true,"finishdate":1212122}
you problem not related json stringify .
the line this.status = detail.status || null;
converts 0
null
.
because 0
falsy this.status
set null
detail.status
being 0
.
you can solve problem either starting itemstatus 1
or not using this.status = detail.status || null;
so either use:
var itemstatus = { 'prepared': 1, 'ongoing': 2, 'finished': 3 };
or test way:
this.status = detail.status; if( this.status !== 0 && !this.status) { this.status = null; }
Comments
Post a Comment