How to deserialize a nested buffer using JSON.parse

I am trying to serialize and deserialize an object that contains several buffers, however, deserializing the resulting string from JSON.stringify () with JSON.parse () does not allow the buffers to be recreated correctly.

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

It gives an output:

 source: Buffer parse: Object 

This makes sense, since the output from Buffer.toJSON () creates a simple object as follows:

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

I assume that I could cross the resulting object that is looking for sub objects that have the above properties and convert them back to a buffer, however I believe there should be a more elegant solution using JSON.parse () that I miss .

+5
source share
2 answers

You can use the function

+11
source

Since JSON serializes Buffer to:

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

You can simply check type and reinitialize the buffer:

 if (source.buf.type === 'Buffer') { source.buf = new Buffer(source.buf.data); } 
+2
source

Source: https://habr.com/ru/post/1239629/


All Articles