diff --git a/lib/Element.js b/lib/Element.js index 7dce18b2..73f6b196 100644 --- a/lib/Element.js +++ b/lib/Element.js @@ -318,6 +318,16 @@ Element.prototype.toString = function () { return s } +Element.prototype.toJSON = function () { + return { + name: this.name, + attrs: this.attrs, + children: this.children.map(function (child) { + return child && child.toJSON ? child.toJSON() : child + }) + } +} + Element.prototype._addChildren = function (writer) { writer('>') for (var i = 0; i < this.children.length; i++) { diff --git a/test/element-test.js b/test/element-test.js index 9ce87bc0..b33db920 100644 --- a/test/element-test.js +++ b/test/element-test.js @@ -82,6 +82,16 @@ vows.describe('Element').addBatch({ 'serialize with integer text': function () { var e = new Element('e').t(1000) assert.equal(e.getText(), 1000) + }, + 'serialize to json': function () { + var e = new Element('e', { foo: 23, bar: 0, nil: null }).c('f').t(1000).up() + assert.deepEqual(e.toJSON(), { + name: 'e', + attrs: { foo: 23, bar: 0, nil: null }, + children: [ + { name: 'f', attrs: {}, children: [1000] } + ] + }) } }, 'remove': {