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?
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])))
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]"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With