Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To get size of json object in bytes, use new TextEncoder().encode(JSON.stringify(obj)).length it will return size in bytes and if you want in kilobyte devide by 1024.

Let’s see short example of javascript get size of json object in bytes.

const obj = {
  id: 1,
  name: "infinitbility",
}
const size = new TextEncoder().encode(JSON.stringify(obj)).length

Today, I’m going to show you How do I get size of json object in bytes in javascript, as above mentioned, I’m going to use the above-mentioned regex with TextEncoder() and JSON.stringify() method.

Let’s start today’s tutorial how do you get size of json object in bytes, kilobytes, MegaBytes in javascript?

Javascript get size of json object in bytes

Here, we will create a sample object and use our TextEncoder() and JSON.stringify() method to get size of json object.

const obj = {
  id: 1,
  name: "infinitbility",
}

const size = new TextEncoder().encode(JSON.stringify(obj)).length
const kiloBytes = size / 1024;
const megaBytes = kiloBytes / 1024;

console.log("size", size);
console.log("kiloBytes", kiloBytes);
console.log("megaBytes", megaBytes);

Output

Node js get size of json object in bytes

Here, we will create a sample object and use our Buffer.byteLength() and JSON.stringify() method to get size of json object.

const obj = {
  id: 1,
  name: "infinitbility",
}

const size = Buffer.byteLength(JSON.stringify(obj))
const kiloBytes = size / 1024;
const megaBytes = kiloBytes / 1024;

console.log("size", size);
console.log("kiloBytes", kiloBytes);
console.log("megaBytes", megaBytes);

Output

I hope it helps you, All the best đź‘Ť.