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]}
5
  • 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. Commented Jan 19, 2023 at 2: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 Commented Jan 19, 2023 at 2:55
  • Tbh it's rather unnormal/unexpected that JSON.stringify(buffer) creates "type": "Buffer" in the output. Commented Jan 19, 2023 at 2:59
  • @Wyck The link you found does the inverse, roundtrip an object (via JSON) through a buffer, not roundtrip a buffer through JSON Commented Jan 19, 2023 at 3:06

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.