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.
pull/41362/head
David Braun 2013-03-26 12:14:52 -03:00 committed by Nathan Rajlich
parent 9b8dd39553
commit 840a29fc0f
3 changed files with 25 additions and 8 deletions

View File

@ -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);
// <Buffer 74 65 73 74>

View File

@ -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)
};
};

View File

@ -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() {