25

Is there JSON encode/decode base64 encode/decode function in JavaScript?

2

5 Answers 5

17

Yes, btoa() and atob() work in some browsers:

var enc = btoa("this is some text");
alert(enc);
alert(atob(enc));
5
  • 17
    "Some browsers" === "Gecko and WebKit"
    – Matt Ball
    Jan 12, 2011 at 3:24
  • 5
    @Matt Ball. Most languages would refute that :)
    – Ben
    Jan 12, 2011 at 3:25
  • 5
    javascript:window.opera && window.btoa && confirm("hi")
    – goat
    Jan 12, 2011 at 3:30
  • Why window.opera? I eliminated that and it works in Firefox and Chrome. Not sure why IE's tools don't let me test JavaScript in the script console thingy. I'll keep looking.
    – vbullinger
    Feb 13, 2013 at 23:16
  • For reference its supported in all browsers since IE 10. caniuse.com/#feat=atob-btoa
    – Nisd
    Nov 1, 2018 at 8:00
5

JSON and base64 are completely independent.

Here's a JSON stringifier/parser (and direct GitHub link).

Here's a base64 Q&A. Here's another one.

4

This might be helpful for you. Using a combination of this project crypto-js and Prototype to parse JSON I wrote two function to encode/decode JSON to Base 64. (These functions don't check for not well formatted json)


    function JSONtoBase64(jsonObj) {
        return Crypto.util.bytesToBase64(Crypto.charenc.UTF8.stringToBytes(Object.toJSON(jsonObj)));
    };

    function base64ToJSON(bytes) {
        var jsonString = Crypto.charenc.UTF8.bytesToString(Crypto.util.base64ToBytes(bytes));
        return jsonString.evalJSON();
    };

2

For non-Mozilla browsers, use: http://www.webtoolkit.info/javascript-base64.html

For Mozilla browsers, use btoa() and atob().

0
0

I don't think there's one built in, but here's the functions for JSON in jquery: (can't post links since I'm new)
jQuery.getJSON
jQuery.parseJSON

and here's a link for base64 encoding in javascript.
http://www.webtoolkit.info/javascript-base64.html

1
  • jQuery.parseJSON has been added in 1.4 and does not work in previous versions.
    – Alexar
    Sep 26, 2011 at 20:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.