• Try this exercise:

    //Uint8Trick.js
    //30 Aug 2016
    var i;
    
    console.log("Create an object with an Uint8Array");
    var A={B:512,C:new Uint8Array(16)};
    for(i=0;i<16;i++)A.C[i]=i;
    console.log("A= ",A);
    
    console.log("Stringify the object");
    var D=JSON.stringify(A);
    console.log("D= ",D);
    
    console.log("Parse it back returns undefined");
    var F=JSON.parse(D);
    console.log("F= ",F); //F is undefined
    
    //notice I skipped E to avoid conflict with E.toUint8Array
    
    //the trick
    console.log("apply btoa trick");
    A.C=btoa(A.C);
    console.log("A= ",A);
    
    console.log("stringify");
    var D=JSON.stringify(A);
    console.log("D= ",D);
    
    console.log("parse");
    var F=JSON.parse(D);
    console.log("F= ",F);
    
    //the trick in reverse
    console.log("reverse the trick");
    F.C=E.toUint8Array(atob(F.C));
    console.log("Frev= ",F);
    

    and the output

    >echo(0);
    Create an object with an Uint8Array
    A=  { "B": 512,
      "C": new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
     }
    Stringify the object
    D=  {"B":512,"C":new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12­,13,14,15])}
    Parse it back returns undefined
    F=  undefined
    apply btoa trick
    A=  { "B": 512,
      "C": "AAECAwQFBgcICQoLDA0ODw=="
     }
    stringify
    D=  {"B":512,"C":"AAECAwQFBgcICQoLDA0ODw=="}­
    parse
    F=  { "B": 512,
      "C": "AAECAwQFBgcICQoLDA0ODw=="
     }
    reverse the trick
    Frev=  { "B": 512,
      "C": new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
     }
    =undefined
    

    1 Attachment

About