Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of json object? (in KBs/MBs)

How can I know that how much data is transferred over wire in terms of size in kilobytes, megabytes?

Take for example

{   'a': 1,   'b': 2 } 

How do I know what is the size of this payload is and not the length or items in the object

UPDATE

content-encoding:gzip content-type:application/json Transfer-Encoding:chunked vary:Accept-Encoding 
like image 202
daydreamer Avatar asked Apr 27 '14 00:04

daydreamer


People also ask

How big is a JSON object?

The maximum length of a JSON type using a binary storage format is 16776192 bytes.


1 Answers

An answer to the actual question should include the bytes spent on the headers and should include taking gzip compression into account, but I will ignore those things.

You have a few options. They all output the same answer when run:

If Using a Browser or Node (Not IE)

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

If you need it to work on IE, you can use a pollyfill

If Using Node

const size = Buffer.byteLength(JSON.stringify(obj)) 

(which is the same as Buffer.byteLength(JSON.stringify(obj), "utf8")).

Shortcut That Works in IE, Modern Browsers, and Node

const size = encodeURI(JSON.stringify(obj)).split(/%..|./).length - 1; 

That last solution will work in almost every case, but that last solution will throw a URIError: URI malformed exception if you feed it input containing a string that should not exist, like let obj = { partOfAnEmoji: "👍🏽"[1] }. The other two solutions I provided will not have that weakness.

(Credits: Credit for the first solution goes here. Credit for the second solution goes to the utf8-byte-length package (which is good, you could use that instead). Most of the credit for that last solution goes to here, but I simplified it a bit. I found the test suite of the utf8-byte-length package super helpful, when researching this.)

like image 91
davidbludlow Avatar answered Sep 21 '22 19:09

davidbludlow