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.
This commit is contained in:
parent
9b8dd39553
commit
840a29fc0f
@ -114,9 +114,8 @@ See `buffer.write()` example, above.
|
|||||||
|
|
||||||
### buf.toJSON()
|
### buf.toJSON()
|
||||||
|
|
||||||
Returns a JSON-representation of the Buffer instance, which is identical to the
|
Returns a JSON-representation of the Buffer instance. `JSON.stringify`
|
||||||
output for JSON Arrays. `JSON.stringify` implicitly calls this function when
|
implicitly calls this function when stringifying a Buffer instance.
|
||||||
stringifying a Buffer instance.
|
|
||||||
|
|
||||||
Example:
|
Example:
|
||||||
|
|
||||||
@ -124,9 +123,13 @@ Example:
|
|||||||
var json = JSON.stringify(buf);
|
var json = JSON.stringify(buf);
|
||||||
|
|
||||||
console.log(json);
|
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);
|
console.log(copy);
|
||||||
// <Buffer 74 65 73 74>
|
// <Buffer 74 65 73 74>
|
||||||
|
@ -379,7 +379,10 @@ Buffer.prototype.write = function(string, offset, length, encoding) {
|
|||||||
|
|
||||||
|
|
||||||
Buffer.prototype.toJSON = function() {
|
Buffer.prototype.toJSON = function() {
|
||||||
return Array.prototype.slice.call(this, 0);
|
return {
|
||||||
|
type: 'Buffer',
|
||||||
|
data: Array.prototype.slice.call(this, 0)
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
@ -833,8 +833,19 @@ Buffer(Buffer(0), 0, 0);
|
|||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
// GH-3905
|
// GH-5110
|
||||||
assert.equal(JSON.stringify(Buffer('test')), '[116,101,115,116]');
|
(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
|
// issue GH-4331
|
||||||
assert.throws(function() {
|
assert.throws(function() {
|
||||||
|
Loading…
x
Reference in New Issue
Block a user