Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript convert an array of bytes to JSON and back

I am having trouble converting a JSON string back to byte array. My byte array was converted to JSON string through JSON.stringify(bytes). If I use JSON.parse to convert the string back to JS, I only get an object, not an array any more. For example in the JS console:

> var bytes = new Int32Array([101, 102, 103]);
> var s = JSON.stringify(bytes);
> s;
"{"0":101,"1":102,"2":103}"
> var a = JSON.parse(s);

> a;
Object {0: 101, 1: 102, 2: 103}

How can I get the original byte array back?

like image 269
user1510580 Avatar asked Sep 02 '14 03:09

user1510580


2 Answers

You can use Array.from to convert a TypedArray into an Array just before the stringification process.

JSON.stringify(Array.from(new Int32Array([101, 102, 103])))
like image 159
Inuart Avatar answered Sep 20 '22 15:09

Inuart


If you want to represent a typed array as an array in JSON and not as an object, you can pass a replacer function as second argument to JSON.stringify and convert the typed array to a normal array first:

var bytes = new Int32Array([101, 102, 103]);
var s = JSON.stringify(bytes, function(k, v) {
    if (v instanceof  Int32Array) {
        return Array.apply([], v);
    }
    return v;
});
// s is now "[101, 102, 103]"
like image 43
Felix Kling Avatar answered Sep 21 '22 15:09

Felix Kling