Search code examples
javascriptarraybuffer

store a json object in ArrayBuffer


Want to store a json object in ArrayBuffer

function stringToUint(string) {
    var string = btoa(unescape(encodeURIComponent(string))),
        charList = string.split(''),
        uintArray = [];
    for (var i = 0; i < charList.length; i++) {
        uintArray.push(charList[i].charCodeAt(0));
    }
    return new Uint8Array(uintArray);
}

function uintToString(uintArray) {
    var encodedString = String.fromCharCode.apply(null, uintArray),
        decodedString = decodeURIComponent(escape(atob(encodedString)));
    return decodedString;
}
var str = {'x':'aaaa'},
    enc = stringToUint(str),
    dec = uintToString(enc);

console.log(dec.x);

console.log(dec.x); is printing `undefined. Am I doing it wrongly ? here is jsfiddle http://jsfiddle.net/DQJyX/137/


Solution

  • Because stringToUint expects a string, and passing an object to it will convert the {'x':'aaaa'} to [Object object] and returns an array representing that object object, and hence on calling uintToString, the array is converted back to [Object object].

    Simple solution is to use JSON.stringify to the object before passing it to function and then using JSON.parse to convert to original object.

    function stringToUint(string) {
        var string = btoa(unescape(encodeURIComponent(string))),
            charList = string.split(''),
            uintArray = [];
        for (var i = 0; i < charList.length; i++) {
            uintArray.push(charList[i].charCodeAt(0));
        }
        return new Uint8Array(uintArray);
    }
    
    function uintToString(uintArray) {
        var encodedString = String.fromCharCode.apply(null, uintArray),
            decodedString = decodeURIComponent(escape(atob(encodedString)));
        return decodedString;
    }
    var str = {'x':'aaaa'},
        enc = stringToUint(JSON.stringify(str)),
        dec = JSON.parse(uintToString(enc));
        
    document.write(dec.x);