How to Convert a javascript object to utf-8 Blob for download?












0














I've been trying to find a solution that works but couldn't find one.



I have an object in javascript and it has some non-english characters in it.

I'm trying the following code to convert the object to a blob for download.

When I click to download the content, when opening the downloaded JSON the non-English characters are gibberish.



It's a simple object like this one: {name: "שלומית", last: "רעננה"}



function setJSONForDownload(obj) {
obj = obj || ; // obj is the array of objects with non-english characters
const length = obj.length;
if (length) {
const str = JSON.stringify(obj);
const data = encode( str );

const blob = new Blob( [ data ], {
type: "application/json;charset=utf-8"
});

const url = URL.createObjectURL( blob );
const downloadElem = document.getElementById('download');
downloadElem.innerText = `Download ${length} pages scraped`;
downloadElem.setAttribute( 'href', url );
downloadElem.setAttribute( 'download', 'data.json' );
}
else {
document.getElementById('download').innerText = `No data to download...`;
}
}

function encode (s) {
const out = ;
for ( let i = 0; i < s.length; i++ ) {
out[i] = s.charCodeAt(i);
}
return new Uint8Array(out);
}









share|improve this question
























  • Can you share the data you set in the blob? it's just a text with non-english characters or it's something else?
    – OriEng
    yesterday










  • Please look at the link-stackoverflow.com/a/53774151/7849549
    – Jai Dixit
    yesterday








  • 1




    Return a Uint16Array(). Char codes are 16 bits, not 8. Then make the type "application/json;charset=utf-16" as well.
    – Patrick Roberts
    yesterday












  • @OriEng it's a simple object like this one: {name: "שלומית", last: "רעננה"}
    – Loves2Develop
    yesterday
















0














I've been trying to find a solution that works but couldn't find one.



I have an object in javascript and it has some non-english characters in it.

I'm trying the following code to convert the object to a blob for download.

When I click to download the content, when opening the downloaded JSON the non-English characters are gibberish.



It's a simple object like this one: {name: "שלומית", last: "רעננה"}



function setJSONForDownload(obj) {
obj = obj || ; // obj is the array of objects with non-english characters
const length = obj.length;
if (length) {
const str = JSON.stringify(obj);
const data = encode( str );

const blob = new Blob( [ data ], {
type: "application/json;charset=utf-8"
});

const url = URL.createObjectURL( blob );
const downloadElem = document.getElementById('download');
downloadElem.innerText = `Download ${length} pages scraped`;
downloadElem.setAttribute( 'href', url );
downloadElem.setAttribute( 'download', 'data.json' );
}
else {
document.getElementById('download').innerText = `No data to download...`;
}
}

function encode (s) {
const out = ;
for ( let i = 0; i < s.length; i++ ) {
out[i] = s.charCodeAt(i);
}
return new Uint8Array(out);
}









share|improve this question
























  • Can you share the data you set in the blob? it's just a text with non-english characters or it's something else?
    – OriEng
    yesterday










  • Please look at the link-stackoverflow.com/a/53774151/7849549
    – Jai Dixit
    yesterday








  • 1




    Return a Uint16Array(). Char codes are 16 bits, not 8. Then make the type "application/json;charset=utf-16" as well.
    – Patrick Roberts
    yesterday












  • @OriEng it's a simple object like this one: {name: "שלומית", last: "רעננה"}
    – Loves2Develop
    yesterday














0












0








0







I've been trying to find a solution that works but couldn't find one.



I have an object in javascript and it has some non-english characters in it.

I'm trying the following code to convert the object to a blob for download.

When I click to download the content, when opening the downloaded JSON the non-English characters are gibberish.



It's a simple object like this one: {name: "שלומית", last: "רעננה"}



function setJSONForDownload(obj) {
obj = obj || ; // obj is the array of objects with non-english characters
const length = obj.length;
if (length) {
const str = JSON.stringify(obj);
const data = encode( str );

const blob = new Blob( [ data ], {
type: "application/json;charset=utf-8"
});

const url = URL.createObjectURL( blob );
const downloadElem = document.getElementById('download');
downloadElem.innerText = `Download ${length} pages scraped`;
downloadElem.setAttribute( 'href', url );
downloadElem.setAttribute( 'download', 'data.json' );
}
else {
document.getElementById('download').innerText = `No data to download...`;
}
}

function encode (s) {
const out = ;
for ( let i = 0; i < s.length; i++ ) {
out[i] = s.charCodeAt(i);
}
return new Uint8Array(out);
}









share|improve this question















I've been trying to find a solution that works but couldn't find one.



I have an object in javascript and it has some non-english characters in it.

I'm trying the following code to convert the object to a blob for download.

When I click to download the content, when opening the downloaded JSON the non-English characters are gibberish.



It's a simple object like this one: {name: "שלומית", last: "רעננה"}



function setJSONForDownload(obj) {
obj = obj || ; // obj is the array of objects with non-english characters
const length = obj.length;
if (length) {
const str = JSON.stringify(obj);
const data = encode( str );

const blob = new Blob( [ data ], {
type: "application/json;charset=utf-8"
});

const url = URL.createObjectURL( blob );
const downloadElem = document.getElementById('download');
downloadElem.innerText = `Download ${length} pages scraped`;
downloadElem.setAttribute( 'href', url );
downloadElem.setAttribute( 'download', 'data.json' );
}
else {
document.getElementById('download').innerText = `No data to download...`;
}
}

function encode (s) {
const out = ;
for ( let i = 0; i < s.length; i++ ) {
out[i] = s.charCodeAt(i);
}
return new Uint8Array(out);
}






javascript json unicode encoding blob






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited yesterday









Mark Schultheiss

23.8k85078




23.8k85078










asked yesterday









Loves2Develop

300214




300214












  • Can you share the data you set in the blob? it's just a text with non-english characters or it's something else?
    – OriEng
    yesterday










  • Please look at the link-stackoverflow.com/a/53774151/7849549
    – Jai Dixit
    yesterday








  • 1




    Return a Uint16Array(). Char codes are 16 bits, not 8. Then make the type "application/json;charset=utf-16" as well.
    – Patrick Roberts
    yesterday












  • @OriEng it's a simple object like this one: {name: "שלומית", last: "רעננה"}
    – Loves2Develop
    yesterday


















  • Can you share the data you set in the blob? it's just a text with non-english characters or it's something else?
    – OriEng
    yesterday










  • Please look at the link-stackoverflow.com/a/53774151/7849549
    – Jai Dixit
    yesterday








  • 1




    Return a Uint16Array(). Char codes are 16 bits, not 8. Then make the type "application/json;charset=utf-16" as well.
    – Patrick Roberts
    yesterday












  • @OriEng it's a simple object like this one: {name: "שלומית", last: "רעננה"}
    – Loves2Develop
    yesterday
















Can you share the data you set in the blob? it's just a text with non-english characters or it's something else?
– OriEng
yesterday




Can you share the data you set in the blob? it's just a text with non-english characters or it's something else?
– OriEng
yesterday












Please look at the link-stackoverflow.com/a/53774151/7849549
– Jai Dixit
yesterday






Please look at the link-stackoverflow.com/a/53774151/7849549
– Jai Dixit
yesterday






1




1




Return a Uint16Array(). Char codes are 16 bits, not 8. Then make the type "application/json;charset=utf-16" as well.
– Patrick Roberts
yesterday






Return a Uint16Array(). Char codes are 16 bits, not 8. Then make the type "application/json;charset=utf-16" as well.
– Patrick Roberts
yesterday














@OriEng it's a simple object like this one: {name: "שלומית", last: "רעננה"}
– Loves2Develop
yesterday




@OriEng it's a simple object like this one: {name: "שלומית", last: "רעננה"}
– Loves2Develop
yesterday












3 Answers
3






active

oldest

votes


















3














Your encode function is broken, as it casts charcodes to bytes. Don't try to implement this yourself, just use the Encoding API:



const str = JSON.stringify(obj);
const bytes = new TextEncoder().encode(str);
const blob = new Blob([bytes], {
type: "application/json;charset=utf-8"
});





share|improve this answer





















  • According to your profile image and this simple code I'm sure you're a magician :) Works like a charm, thanks!
    – Loves2Develop
    yesterday






  • 1




    While it won't be a problem here, because it won't be used, note that even if not per se forbidden, setting the ;charset=nnn will make your MIMEType invalid to some browsers (Safari at least). Better not set it, it doesn't have any incidence whatsoever on the content anyway.
    – Kaiido
    20 hours ago








  • 2




    And I missed it earlier, but the conversion DOMString to UTF-8 is implicitly done by new Blob([DOMString])
    – Kaiido
    19 hours ago












  • @Kaiido Thanks, I had guessed there was something even simpler but didn't take the time to look it up. Have an upvote!
    – Bergi
    18 hours ago





















1














Calling new Blob([DOMString]) will automatically convert your DOMString (UTF-16) to UTF-8.



So all you need is new Blob( [JSON.stringify(obj)] ).



Note that the type won't get used here (it would be only if there was a fetching or if you actually tried to read the Blob), and will anyway only have incidence on how the file might get read (i.e by FileReader.readAsText()), but not on the actual content of the file, so no need to set it.






setJSONForDownload([{ name: "שלומית", last: "רעננה"}]);

function setJSONForDownload(obj) {
obj = obj || ;
const length = obj.length;
if (length) {

// DOMString
const str = JSON.stringify(obj);
// text/plain;UTF-8
const blob = new Blob([str]);

const url = URL.createObjectURL(blob);
const downloadElem = document.getElementById('download');
downloadElem.innerText = `Download ${length} pages scraped`;
downloadElem.setAttribute('href', url);
downloadElem.setAttribute('download', 'data.json');
} else {
document.getElementById('download').innerText = `No data to download...`;
}
}

<a id="download">dl</a>








share|improve this answer





























    0














    I found a nice block of code that solved my issue.

    Thanks to 'pascaldekloe' (https://gist.github.com/pascaldekloe/62546103a1576803dade9269ccf76330).



    Just changed the encode method to the following:



    function encode(s) {
    var i = 0, bytes = new Uint8Array(s.length * 4);
    for (var ci = 0; ci != s.length; ci++) {
    var c = s.charCodeAt(ci);
    if (c < 128) {
    bytes[i++] = c;
    continue;
    }
    if (c < 2048) {
    bytes[i++] = c >> 6 | 192;
    } else {
    if (c > 0xd7ff && c < 0xdc00) {
    if (++ci >= s.length)
    throw new Error('UTF-8 encode: incomplete surrogate pair');
    var c2 = s.charCodeAt(ci);
    if (c2 < 0xdc00 || c2 > 0xdfff)
    throw new Error('UTF-8 encode: second surrogate character 0x' + c2.toString(16) + ' at index ' + ci + ' out of range');
    c = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff);
    bytes[i++] = c >> 18 | 240;
    bytes[i++] = c >> 12 & 63 | 128;
    } else bytes[i++] = c >> 12 | 224;
    bytes[i++] = c >> 6 & 63 | 128;
    }
    bytes[i++] = c & 63 | 128;
    }
    return bytes.subarray(0, i);
    }





    share|improve this answer





















      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53929108%2fhow-to-convert-a-javascript-object-to-utf-8-blob-for-download%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      3














      Your encode function is broken, as it casts charcodes to bytes. Don't try to implement this yourself, just use the Encoding API:



      const str = JSON.stringify(obj);
      const bytes = new TextEncoder().encode(str);
      const blob = new Blob([bytes], {
      type: "application/json;charset=utf-8"
      });





      share|improve this answer





















      • According to your profile image and this simple code I'm sure you're a magician :) Works like a charm, thanks!
        – Loves2Develop
        yesterday






      • 1




        While it won't be a problem here, because it won't be used, note that even if not per se forbidden, setting the ;charset=nnn will make your MIMEType invalid to some browsers (Safari at least). Better not set it, it doesn't have any incidence whatsoever on the content anyway.
        – Kaiido
        20 hours ago








      • 2




        And I missed it earlier, but the conversion DOMString to UTF-8 is implicitly done by new Blob([DOMString])
        – Kaiido
        19 hours ago












      • @Kaiido Thanks, I had guessed there was something even simpler but didn't take the time to look it up. Have an upvote!
        – Bergi
        18 hours ago


















      3














      Your encode function is broken, as it casts charcodes to bytes. Don't try to implement this yourself, just use the Encoding API:



      const str = JSON.stringify(obj);
      const bytes = new TextEncoder().encode(str);
      const blob = new Blob([bytes], {
      type: "application/json;charset=utf-8"
      });





      share|improve this answer





















      • According to your profile image and this simple code I'm sure you're a magician :) Works like a charm, thanks!
        – Loves2Develop
        yesterday






      • 1




        While it won't be a problem here, because it won't be used, note that even if not per se forbidden, setting the ;charset=nnn will make your MIMEType invalid to some browsers (Safari at least). Better not set it, it doesn't have any incidence whatsoever on the content anyway.
        – Kaiido
        20 hours ago








      • 2




        And I missed it earlier, but the conversion DOMString to UTF-8 is implicitly done by new Blob([DOMString])
        – Kaiido
        19 hours ago












      • @Kaiido Thanks, I had guessed there was something even simpler but didn't take the time to look it up. Have an upvote!
        – Bergi
        18 hours ago
















      3












      3








      3






      Your encode function is broken, as it casts charcodes to bytes. Don't try to implement this yourself, just use the Encoding API:



      const str = JSON.stringify(obj);
      const bytes = new TextEncoder().encode(str);
      const blob = new Blob([bytes], {
      type: "application/json;charset=utf-8"
      });





      share|improve this answer












      Your encode function is broken, as it casts charcodes to bytes. Don't try to implement this yourself, just use the Encoding API:



      const str = JSON.stringify(obj);
      const bytes = new TextEncoder().encode(str);
      const blob = new Blob([bytes], {
      type: "application/json;charset=utf-8"
      });






      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered yesterday









      Bergi

      363k57540864




      363k57540864












      • According to your profile image and this simple code I'm sure you're a magician :) Works like a charm, thanks!
        – Loves2Develop
        yesterday






      • 1




        While it won't be a problem here, because it won't be used, note that even if not per se forbidden, setting the ;charset=nnn will make your MIMEType invalid to some browsers (Safari at least). Better not set it, it doesn't have any incidence whatsoever on the content anyway.
        – Kaiido
        20 hours ago








      • 2




        And I missed it earlier, but the conversion DOMString to UTF-8 is implicitly done by new Blob([DOMString])
        – Kaiido
        19 hours ago












      • @Kaiido Thanks, I had guessed there was something even simpler but didn't take the time to look it up. Have an upvote!
        – Bergi
        18 hours ago




















      • According to your profile image and this simple code I'm sure you're a magician :) Works like a charm, thanks!
        – Loves2Develop
        yesterday






      • 1




        While it won't be a problem here, because it won't be used, note that even if not per se forbidden, setting the ;charset=nnn will make your MIMEType invalid to some browsers (Safari at least). Better not set it, it doesn't have any incidence whatsoever on the content anyway.
        – Kaiido
        20 hours ago








      • 2




        And I missed it earlier, but the conversion DOMString to UTF-8 is implicitly done by new Blob([DOMString])
        – Kaiido
        19 hours ago












      • @Kaiido Thanks, I had guessed there was something even simpler but didn't take the time to look it up. Have an upvote!
        – Bergi
        18 hours ago


















      According to your profile image and this simple code I'm sure you're a magician :) Works like a charm, thanks!
      – Loves2Develop
      yesterday




      According to your profile image and this simple code I'm sure you're a magician :) Works like a charm, thanks!
      – Loves2Develop
      yesterday




      1




      1




      While it won't be a problem here, because it won't be used, note that even if not per se forbidden, setting the ;charset=nnn will make your MIMEType invalid to some browsers (Safari at least). Better not set it, it doesn't have any incidence whatsoever on the content anyway.
      – Kaiido
      20 hours ago






      While it won't be a problem here, because it won't be used, note that even if not per se forbidden, setting the ;charset=nnn will make your MIMEType invalid to some browsers (Safari at least). Better not set it, it doesn't have any incidence whatsoever on the content anyway.
      – Kaiido
      20 hours ago






      2




      2




      And I missed it earlier, but the conversion DOMString to UTF-8 is implicitly done by new Blob([DOMString])
      – Kaiido
      19 hours ago






      And I missed it earlier, but the conversion DOMString to UTF-8 is implicitly done by new Blob([DOMString])
      – Kaiido
      19 hours ago














      @Kaiido Thanks, I had guessed there was something even simpler but didn't take the time to look it up. Have an upvote!
      – Bergi
      18 hours ago






      @Kaiido Thanks, I had guessed there was something even simpler but didn't take the time to look it up. Have an upvote!
      – Bergi
      18 hours ago















      1














      Calling new Blob([DOMString]) will automatically convert your DOMString (UTF-16) to UTF-8.



      So all you need is new Blob( [JSON.stringify(obj)] ).



      Note that the type won't get used here (it would be only if there was a fetching or if you actually tried to read the Blob), and will anyway only have incidence on how the file might get read (i.e by FileReader.readAsText()), but not on the actual content of the file, so no need to set it.






      setJSONForDownload([{ name: "שלומית", last: "רעננה"}]);

      function setJSONForDownload(obj) {
      obj = obj || ;
      const length = obj.length;
      if (length) {

      // DOMString
      const str = JSON.stringify(obj);
      // text/plain;UTF-8
      const blob = new Blob([str]);

      const url = URL.createObjectURL(blob);
      const downloadElem = document.getElementById('download');
      downloadElem.innerText = `Download ${length} pages scraped`;
      downloadElem.setAttribute('href', url);
      downloadElem.setAttribute('download', 'data.json');
      } else {
      document.getElementById('download').innerText = `No data to download...`;
      }
      }

      <a id="download">dl</a>








      share|improve this answer


























        1














        Calling new Blob([DOMString]) will automatically convert your DOMString (UTF-16) to UTF-8.



        So all you need is new Blob( [JSON.stringify(obj)] ).



        Note that the type won't get used here (it would be only if there was a fetching or if you actually tried to read the Blob), and will anyway only have incidence on how the file might get read (i.e by FileReader.readAsText()), but not on the actual content of the file, so no need to set it.






        setJSONForDownload([{ name: "שלומית", last: "רעננה"}]);

        function setJSONForDownload(obj) {
        obj = obj || ;
        const length = obj.length;
        if (length) {

        // DOMString
        const str = JSON.stringify(obj);
        // text/plain;UTF-8
        const blob = new Blob([str]);

        const url = URL.createObjectURL(blob);
        const downloadElem = document.getElementById('download');
        downloadElem.innerText = `Download ${length} pages scraped`;
        downloadElem.setAttribute('href', url);
        downloadElem.setAttribute('download', 'data.json');
        } else {
        document.getElementById('download').innerText = `No data to download...`;
        }
        }

        <a id="download">dl</a>








        share|improve this answer
























          1












          1








          1






          Calling new Blob([DOMString]) will automatically convert your DOMString (UTF-16) to UTF-8.



          So all you need is new Blob( [JSON.stringify(obj)] ).



          Note that the type won't get used here (it would be only if there was a fetching or if you actually tried to read the Blob), and will anyway only have incidence on how the file might get read (i.e by FileReader.readAsText()), but not on the actual content of the file, so no need to set it.






          setJSONForDownload([{ name: "שלומית", last: "רעננה"}]);

          function setJSONForDownload(obj) {
          obj = obj || ;
          const length = obj.length;
          if (length) {

          // DOMString
          const str = JSON.stringify(obj);
          // text/plain;UTF-8
          const blob = new Blob([str]);

          const url = URL.createObjectURL(blob);
          const downloadElem = document.getElementById('download');
          downloadElem.innerText = `Download ${length} pages scraped`;
          downloadElem.setAttribute('href', url);
          downloadElem.setAttribute('download', 'data.json');
          } else {
          document.getElementById('download').innerText = `No data to download...`;
          }
          }

          <a id="download">dl</a>








          share|improve this answer












          Calling new Blob([DOMString]) will automatically convert your DOMString (UTF-16) to UTF-8.



          So all you need is new Blob( [JSON.stringify(obj)] ).



          Note that the type won't get used here (it would be only if there was a fetching or if you actually tried to read the Blob), and will anyway only have incidence on how the file might get read (i.e by FileReader.readAsText()), but not on the actual content of the file, so no need to set it.






          setJSONForDownload([{ name: "שלומית", last: "רעננה"}]);

          function setJSONForDownload(obj) {
          obj = obj || ;
          const length = obj.length;
          if (length) {

          // DOMString
          const str = JSON.stringify(obj);
          // text/plain;UTF-8
          const blob = new Blob([str]);

          const url = URL.createObjectURL(blob);
          const downloadElem = document.getElementById('download');
          downloadElem.innerText = `Download ${length} pages scraped`;
          downloadElem.setAttribute('href', url);
          downloadElem.setAttribute('download', 'data.json');
          } else {
          document.getElementById('download').innerText = `No data to download...`;
          }
          }

          <a id="download">dl</a>








          setJSONForDownload([{ name: "שלומית", last: "רעננה"}]);

          function setJSONForDownload(obj) {
          obj = obj || ;
          const length = obj.length;
          if (length) {

          // DOMString
          const str = JSON.stringify(obj);
          // text/plain;UTF-8
          const blob = new Blob([str]);

          const url = URL.createObjectURL(blob);
          const downloadElem = document.getElementById('download');
          downloadElem.innerText = `Download ${length} pages scraped`;
          downloadElem.setAttribute('href', url);
          downloadElem.setAttribute('download', 'data.json');
          } else {
          document.getElementById('download').innerText = `No data to download...`;
          }
          }

          <a id="download">dl</a>





          setJSONForDownload([{ name: "שלומית", last: "רעננה"}]);

          function setJSONForDownload(obj) {
          obj = obj || ;
          const length = obj.length;
          if (length) {

          // DOMString
          const str = JSON.stringify(obj);
          // text/plain;UTF-8
          const blob = new Blob([str]);

          const url = URL.createObjectURL(blob);
          const downloadElem = document.getElementById('download');
          downloadElem.innerText = `Download ${length} pages scraped`;
          downloadElem.setAttribute('href', url);
          downloadElem.setAttribute('download', 'data.json');
          } else {
          document.getElementById('download').innerText = `No data to download...`;
          }
          }

          <a id="download">dl</a>






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 20 hours ago









          Kaiido

          38.8k45799




          38.8k45799























              0














              I found a nice block of code that solved my issue.

              Thanks to 'pascaldekloe' (https://gist.github.com/pascaldekloe/62546103a1576803dade9269ccf76330).



              Just changed the encode method to the following:



              function encode(s) {
              var i = 0, bytes = new Uint8Array(s.length * 4);
              for (var ci = 0; ci != s.length; ci++) {
              var c = s.charCodeAt(ci);
              if (c < 128) {
              bytes[i++] = c;
              continue;
              }
              if (c < 2048) {
              bytes[i++] = c >> 6 | 192;
              } else {
              if (c > 0xd7ff && c < 0xdc00) {
              if (++ci >= s.length)
              throw new Error('UTF-8 encode: incomplete surrogate pair');
              var c2 = s.charCodeAt(ci);
              if (c2 < 0xdc00 || c2 > 0xdfff)
              throw new Error('UTF-8 encode: second surrogate character 0x' + c2.toString(16) + ' at index ' + ci + ' out of range');
              c = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff);
              bytes[i++] = c >> 18 | 240;
              bytes[i++] = c >> 12 & 63 | 128;
              } else bytes[i++] = c >> 12 | 224;
              bytes[i++] = c >> 6 & 63 | 128;
              }
              bytes[i++] = c & 63 | 128;
              }
              return bytes.subarray(0, i);
              }





              share|improve this answer


























                0














                I found a nice block of code that solved my issue.

                Thanks to 'pascaldekloe' (https://gist.github.com/pascaldekloe/62546103a1576803dade9269ccf76330).



                Just changed the encode method to the following:



                function encode(s) {
                var i = 0, bytes = new Uint8Array(s.length * 4);
                for (var ci = 0; ci != s.length; ci++) {
                var c = s.charCodeAt(ci);
                if (c < 128) {
                bytes[i++] = c;
                continue;
                }
                if (c < 2048) {
                bytes[i++] = c >> 6 | 192;
                } else {
                if (c > 0xd7ff && c < 0xdc00) {
                if (++ci >= s.length)
                throw new Error('UTF-8 encode: incomplete surrogate pair');
                var c2 = s.charCodeAt(ci);
                if (c2 < 0xdc00 || c2 > 0xdfff)
                throw new Error('UTF-8 encode: second surrogate character 0x' + c2.toString(16) + ' at index ' + ci + ' out of range');
                c = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff);
                bytes[i++] = c >> 18 | 240;
                bytes[i++] = c >> 12 & 63 | 128;
                } else bytes[i++] = c >> 12 | 224;
                bytes[i++] = c >> 6 & 63 | 128;
                }
                bytes[i++] = c & 63 | 128;
                }
                return bytes.subarray(0, i);
                }





                share|improve this answer
























                  0












                  0








                  0






                  I found a nice block of code that solved my issue.

                  Thanks to 'pascaldekloe' (https://gist.github.com/pascaldekloe/62546103a1576803dade9269ccf76330).



                  Just changed the encode method to the following:



                  function encode(s) {
                  var i = 0, bytes = new Uint8Array(s.length * 4);
                  for (var ci = 0; ci != s.length; ci++) {
                  var c = s.charCodeAt(ci);
                  if (c < 128) {
                  bytes[i++] = c;
                  continue;
                  }
                  if (c < 2048) {
                  bytes[i++] = c >> 6 | 192;
                  } else {
                  if (c > 0xd7ff && c < 0xdc00) {
                  if (++ci >= s.length)
                  throw new Error('UTF-8 encode: incomplete surrogate pair');
                  var c2 = s.charCodeAt(ci);
                  if (c2 < 0xdc00 || c2 > 0xdfff)
                  throw new Error('UTF-8 encode: second surrogate character 0x' + c2.toString(16) + ' at index ' + ci + ' out of range');
                  c = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff);
                  bytes[i++] = c >> 18 | 240;
                  bytes[i++] = c >> 12 & 63 | 128;
                  } else bytes[i++] = c >> 12 | 224;
                  bytes[i++] = c >> 6 & 63 | 128;
                  }
                  bytes[i++] = c & 63 | 128;
                  }
                  return bytes.subarray(0, i);
                  }





                  share|improve this answer












                  I found a nice block of code that solved my issue.

                  Thanks to 'pascaldekloe' (https://gist.github.com/pascaldekloe/62546103a1576803dade9269ccf76330).



                  Just changed the encode method to the following:



                  function encode(s) {
                  var i = 0, bytes = new Uint8Array(s.length * 4);
                  for (var ci = 0; ci != s.length; ci++) {
                  var c = s.charCodeAt(ci);
                  if (c < 128) {
                  bytes[i++] = c;
                  continue;
                  }
                  if (c < 2048) {
                  bytes[i++] = c >> 6 | 192;
                  } else {
                  if (c > 0xd7ff && c < 0xdc00) {
                  if (++ci >= s.length)
                  throw new Error('UTF-8 encode: incomplete surrogate pair');
                  var c2 = s.charCodeAt(ci);
                  if (c2 < 0xdc00 || c2 > 0xdfff)
                  throw new Error('UTF-8 encode: second surrogate character 0x' + c2.toString(16) + ' at index ' + ci + ' out of range');
                  c = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff);
                  bytes[i++] = c >> 18 | 240;
                  bytes[i++] = c >> 12 & 63 | 128;
                  } else bytes[i++] = c >> 12 | 224;
                  bytes[i++] = c >> 6 & 63 | 128;
                  }
                  bytes[i++] = c & 63 | 128;
                  }
                  return bytes.subarray(0, i);
                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered yesterday









                  Loves2Develop

                  300214




                  300214






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53929108%2fhow-to-convert-a-javascript-object-to-utf-8-blob-for-download%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Monofisismo

                      Angular Downloading a file using contenturl with Basic Authentication

                      Olmecas