Kevin
Kevin

Reputation: 23634

How to check the size of a JSON response?

Is there any way I can check the response size? Data property is a byte array which I am using to display an image. If the size is greater than 10 MB I need to show a popup.

{
  "Name": "sharon",
  "Date": "07\/14\/2004",
  "Data": "JVBERi0xLjINCg0KNC",
  "DocumentId":1540,
}

Also how can I check the type of my response, whether it's blob or something? Can I check the size of the blob I am getting? Maybe something like this:

var data = JSON.parse(this.responseData);

Upvotes: 3

Views: 5102

Answers (2)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48693

You can slurp the incoming response into one line and remove all unnecessary white-space.

var JSON = '{\r\n' +
'   "Name": "sharon",\r\n' +
'   "Date": "07\/14\/2004",\r\n' +
'   "Data": "JVBERi0xLjINCg0KNC",\r\n' +
'   "DocumentId":1540,\r\n' +
'}';
alert(JSON);
alert(JSON.length); // 101

var newJSON = slurp(JSON);
alert(newJSON);
alert(newJSON.length); // 91

function slurp(str) {
  str = str.replace(/(\r\n|\n|\r)/gm,"");
  str = str.replace(/(\s+|\t)/gm,' ');
  return str;
}

Upvotes: 0

arttronics
arttronics

Reputation: 9955

You simply can use JavaScript .length for this, but do realize different browsers as well as servers will report different values since some interpretation of newlines can be 1 of 2 size values (byte-order).

Having said that, use a "loose" value that your sure contains the data you need, and not just the header response that has no value.

Upvotes: 1

Related Questions