0

I have some existing code that is working with Buffer objects.

let dataObject = JSON.parse(JSON.stringify(data));

Which seems to me like a no-op, ie it doesn't do anything. That's not correct though, as if I replace it with:

let dataObject = data;

The code fails. I've some some investigation and:

  • typeof data is object
  • data.constructor.name is Object
  • data when logged is <Buffer>... (long stream of bytes)

What does JSON.parse(JSON.stringify(buffer)) do? Is there a better or clearer way of doing this?

1 Answer 1

1

The buf.toJSON() method has a misleading name because it returns a JavaScript object, while JSON is actually a string data format. However, it returns a representation of the Buffer and the data it contains, so you can replace this:

let dataObject = JSON.parse(JSON.stringify(data));

With this cleaner code:

let dataObject = data.toJSON();
Sign up to request clarification or add additional context in comments.

4 Comments

Sorry I made a mistake in my question, data.constructor.name is Object. I am trying to apply your answer but it does not work (data.toJSON is not a function). The confusion may be my fault.
I don't know what kind of object has Object as the constructor and displays Buffer when being logged (probably some kind of incomplete inheritance). Have you tried Buffer.prototype.toJSON.call(data)? If that doesn't work, you should add details on the prototype chain of the object you have, or the code that generates it.
Wouldn't the equivalent of JSON.parse(JSON.stringify(<Buffer>)); be <Buffer>.toJSON() directly instead of getting the .data property afterwards?
@Kaiido yes indeed I just tested it and noticed you were right. Fixed.

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.