From 840a29fc0fd256a63b3f2f5e7528de5107a608a3 Mon Sep 17 00:00:00 2001 From: David Braun Date: Tue, 26 Mar 2013 12:14:52 -0300 Subject: [PATCH] buffer: change output of Buffer.prototype.toJSON() Expand the JSON representation of Buffer to include type information so that it can be deserialized in JSON.parse() without context. Fixes #5110. Fixes #5143. --- doc/api/buffer.markdown | 13 ++++++++----- lib/buffer.js | 5 ++++- test/simple/test-buffer.js | 15 +++++++++++++-- 3 files changed, 25 insertions(+), 8 deletions(-) diff --git a/doc/api/buffer.markdown b/doc/api/buffer.markdown index 268294fce08..f0c1c1c16ba 100644 --- a/doc/api/buffer.markdown +++ b/doc/api/buffer.markdown @@ -114,9 +114,8 @@ See `buffer.write()` example, above. ### buf.toJSON() -Returns a JSON-representation of the Buffer instance, which is identical to the -output for JSON Arrays. `JSON.stringify` implicitly calls this function when -stringifying a Buffer instance. +Returns a JSON-representation of the Buffer instance. `JSON.stringify` +implicitly calls this function when stringifying a Buffer instance. Example: @@ -124,9 +123,13 @@ Example: var json = JSON.stringify(buf); console.log(json); - // '[116,101,115,116]' + // '{"type":"Buffer","data":[116,101,115,116]}' - var copy = new Buffer(JSON.parse(json)); + var copy = JSON.parse(json, function(key, value) { + return value && value.type === 'Buffer' + ? new Buffer(value.data) + : value; + }); console.log(copy); // diff --git a/lib/buffer.js b/lib/buffer.js index 20b3f02c1c0..24ca3bbbef4 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -379,7 +379,10 @@ Buffer.prototype.write = function(string, offset, length, encoding) { Buffer.prototype.toJSON = function() { - return Array.prototype.slice.call(this, 0); + return { + type: 'Buffer', + data: Array.prototype.slice.call(this, 0) + }; }; diff --git a/test/simple/test-buffer.js b/test/simple/test-buffer.js index 6962c75c4c5..4bbb3c06866 100644 --- a/test/simple/test-buffer.js +++ b/test/simple/test-buffer.js @@ -833,8 +833,19 @@ Buffer(Buffer(0), 0, 0); }); -// GH-3905 -assert.equal(JSON.stringify(Buffer('test')), '[116,101,115,116]'); +// GH-5110 +(function () { + var buffer = new Buffer('test'), + string = JSON.stringify(buffer); + + assert.equal(string, '{"type":"Buffer","data":[116,101,115,116]}'); + + assert.deepEqual(buffer, JSON.parse(string, function(key, value) { + return value && value.type === 'Buffer' + ? new Buffer(value.data) + : value; + })); +})(); // issue GH-4331 assert.throws(function() {