Book Image

JavaScript JSON Cookbook

By : Ray Rischpater, Brian Ritchie, Ray Rischpater
Book Image

JavaScript JSON Cookbook

By: Ray Rischpater, Brian Ritchie, Ray Rischpater

Overview of this book

Table of Contents (17 chapters)
JavaScript JSON Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Using a DataView to access an ArrayBuffer


Sometimes, you don't want to work with JSON at all, but instead with pure binary data. JavaScript provides the DataView abstraction, which lets you perform typed accesses on an array buffer of memory, such as one obtained from an XMLHttpRequest object.

Getting ready

To begin, you need your data in an ArrayBuffer, such as the one returned by the XMLHttpRequest object. With this, you can create a DataView, and then using that DataArray, create a typed array over the data view to extract just the bytes that you're interested in. Let's see an example.

How to do it…

Here's a simple example:

var req = new XMLHttpRequest();
req.open("GET", url, true);
req.responseType = "arraybuffer";
req.onreadystatechange = function () {
  if (req.readyState == req.DONE) {
    var arrayResponse = req.response;
    var dataView = new DataView(arrayResponse);
    var ints = new Uint32Array(dataView.byteLength / 4);

    // process each int in ints here.

    }
}
req.send();

How...