Skip to content

Instantly share code, notes, and snippets.

@manelet
Last active January 30, 2019 18:44
Show Gist options
  • Save manelet/7d67507bbc6c27029905960ee1b156cd to your computer and use it in GitHub Desktop.
Save manelet/7d67507bbc6c27029905960ee1b156cd to your computer and use it in GitHub Desktop.
Encode/decode JSON like objects to ArrayBuffers
// ENCODE
var object = { dd: "ddd", sub: { xx: "dd" }, num: 666 }
var string = JSON.stringify(object)
var uint8_array = new TextEncoder('utf-8').encode(string)
var array_buffer = uint8_array.buffer
// DECODE
var array_buffer = new Uint8Array([123,34,100,100,34,58,34,100,100,100,34,44,34,115,117,98,34,58,123,34,120,120,34,58,34,100,100,34,125,44,34,110,117,109,34,58,54,54,54,125]).buffer
var decoder = new TextDecoder('utf-8')
var view = new DataView(array_buffer, 0, array_buffer.byteLength)
var string = decoder.decode(view)
var object = JSON.parse(string)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment