0

It looks like JSON does not parse into an actual type. Is this normal and expected behaviour for JSON.parse?

let parseBuf = JSON.parse('{"type":"Buffer","data":[146,247,204,173,154,172,70,6,147,130,219,222,4,69,161,74]}');
let bufferBuf = Buffer.from(parseBuf.data);

console.log(parseBuf instanceof Buffer)
console.log(bufferBuf instanceof Buffer)

console.log(JSON.stringify(parseBuf))
console.log(JSON.stringify(bufferBuf))

Results from the console log is

false
true
{"type":"Buffer","data":[146,247,204,173,154,172,70,6,147,130,219,222,4,69,161,74]}
{"type":"Buffer","data":[146,247,204,173,154,172,70,6,147,130,219,222,4,69,161,74]}
Beraben Systems
  • 103
  • 1
  • 1
  • 9
  • 2
    Yes, that's normal and expected behavior. `JSON.parse` returns a JS value or object. A Buffer is not a JS value or object, it's a Node-specific object. – Zac Anger Jan 19 '23 at 02:52
  • 1
    Yes, that's as expected. You have to turn the JavaScript object that JSON.parse produces (the one that looks like `{"type": "Buffer", "data":[...]}` into a `Buffer` with `Buffer.from` as you did in the second line of your example. JSON knows very few types: string, number, array, object, boolean, null. Notoriously unsupported are: Buffer, Date, function, and undefined. Consider reading [Convert a JSON Object to Buffer and Buffer to JSON Object back](https://stackoverflow.com/questions/41951307/convert-a-json-object-to-buffer-and-buffer-to-json-object-back) – Wyck Jan 19 '23 at 02:55
  • Tbh it's rather unnormal/unexpected that `JSON.stringify(buffer)` creates `"type": "Buffer"` in the output. – Bergi Jan 19 '23 at 02:59
  • See https://stackoverflow.com/questions/5873624/parse-json-string-into-a-particular-object-prototype-in-javascript, https://stackoverflow.com/questions/52315147/json-to-javascript-class and https://stackoverflow.com/questions/12975430/custom-object-to-json-then-back-to-a-custom-object – Bergi Jan 19 '23 at 03:01
  • @Wyck The link you found does the inverse, roundtrip an object (via JSON) through a buffer, not roundtrip a buffer through JSON – Bergi Jan 19 '23 at 03:06

0 Answers0