Sometimes, we want to get the size of JSON object with JavaScript.
In this article, we’ll look at how to get the size of JSON object with JavaScript.
How to get the size of JSON object with JavaScript?
To get the size of JSON object with JavaScript, we use the TextEncode
constructor.
For instance, we write
const size = new TextEncoder().encode(JSON.stringify(obj)).length;
const kiloBytes = size / 1024;
const megaBytes = kiloBytes / 1024;
to create a TextEncoder
object and call its encode
method with the JSON string we want to get the size of.
Then we get the size of that with length
in bytes.
Next, we get the size in KB and MB by dividing each by 1024.
Conclusion
To get the size of JSON object with JavaScript, we use the TextEncode
constructor.