Skip to main content
Deno 2 is finally here 🎉️
Learn more
Module

std/node/buffer.ts>Buffer#toJSON

Deno standard library
Go to Latest
The Standard Library has been moved to JSR. See the blog post for details.
method Buffer.prototype.toJSON
import { Buffer } from "https://deno.land/std@0.162.0/node/buffer.ts";

Returns a JSON representation of buf. JSON.stringify() implicitly calls this function when stringifying a Buffer instance.

Buffer.from() accepts objects in the format returned from this method. In particular, Buffer.from(buf.toJSON()) works like Buffer.from(buf).

import { Buffer } from 'buffer';

const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
const json = JSON.stringify(buf);

console.log(json);
// Prints: {"type":"Buffer","data":[1,2,3,4,5]}

const copy = JSON.parse(json, (key, value) => {
  return value && value.type === 'Buffer' ?
    Buffer.from(value) :
    value;
});

console.log(copy);
// Prints: <Buffer 01 02 03 04 05>

Returns

{ type: "Buffer"; data: number[]; }