Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize a nested Buffer using JSON.parse

I am trying to serialise and deserialise an object which contains multiple Buffers, however deserialising the resulting string from JSON.stringify() with JSON.parse() fails to correctly re-create the Buffers.

var b64 = 'Jw8mm8h+agVwgI/yN1egchSax0WLWXSEVP0umVvv5zM='; 
var buf = new Buffer(b64, 'base64');

var source = {
    a: {
        buffer: buf
    }
};

var stringify = JSON.stringify(source);
var parse = JSON.parse(stringify);

console.log("source: "+source.a.buffer.constructor.name);
console.log("parse: "+parse.a.buffer.constructor.name);

Gives the ouput:

source: Buffer
parse: Object

This makes sense since the output from Buffer.toJSON() creates a simple object like so:

{
  type: "Buffer",
  data: [...]
}

I guess I could traverse the resulting object looking for sub objects that have the above properties and convert them back to a Buffer, however I feel there should be a more elegant solution using JSON.parse() that I am missing.

like image 831
GeekyDeaks Avatar asked Jan 01 '16 16:01

GeekyDeaks


1 Answers

You could use a reviver function that checks if an object looks like a stringified Buffer, and create a proper instance from it:

var parse = JSON.parse(stringify, (k, v) => {
  if (
    v !== null            &&
    typeof v === 'object' && 
    'type' in v           &&
    v.type === 'Buffer'   &&
    'data' in v           &&
    Array.isArray(v.data)) {
    return new Buffer(v.data);
  }
  return v;
});
like image 123
robertklep Avatar answered Sep 22 '22 12:09

robertklep