Native JSON in Firefox 3.1

Ryan Doherty

16

In case you haven’t heard, one of Firefox 3.1’s awesome new features will be native JSON support. This is totally sweet for two reasons:

  1. eval’ing JSON in the browser is unsafe. Using native JSON parsing protects you against possible code execution.
  2. Safely eval’ing JSON with a 3rd party library can be orders of magnitude slower. Native JSON parsing is much faster.

How does native JSON work compared to plain old eval? Simple:

var jsonString = '{"name":"Ryan", "address":"Mountain View, CA"}';
var person = JSON.parse(jsonString);
// 'person' is now a JavaScript object with 2 properties; name and address

Pretty easy huh? And here’s how to get a JSON string from an object:

var personString = JSON.stringify(person);
// 'personString' now holds the string '{"name":"Ryan", "address":"Mountain View, CA"}'

“But wait!”, you say. “How is it safer? How much faster is it compared to eval?”. Ok, I’ll show you.

Native JSON parsing in Firefox 3.1 is safer because it does not support objects with functions. Attempting to convert an object with functions into a JSON string will only convert its properties and not its functions. And any malformed JSON string will result in a parse error instead of possible code execution.

Now, regarding speed, native JSON parsing is faster, much faster. Instead of pretty charts and graphs, I’ll give you a real-world example.

The new Graph Server uses a JSON API to fetch test information and results, so I figured it would be a good application to benchmark. So I wrapped our code that parses the JSON response with some Firebug profiler calls:

    console.time('parsejson');
    var obj = eval('(' + resp + ')');
    console.timeEnd('parsejson');

Loading a test’s results (array with 3,000 indexes, 24k gzipped) gave me a time of 125ms. (Repeated tests yielded results +/- 5ms). Then I changed eval to JSON.parse:

    console.time('parsejson');
    var obj = JSON.parse(resp);
    console.timeEnd('parsejson');

Which resulted in an average time of 40ms! That’s about 2.7 times faster with 1 line of code changed. Not bad!

Granted, a difference of 80ms isn’t that much, but in an AJAX (or, more accurately, AJAJ?) application, it can add up.

What’s the use of native JSON if it’s only available in Firefox? Luckily, IE8 has implemented it in RC1, which is rumored to be released in March. Hopefully other browsers will follow suit too, but for now it’s best to use a JSON parser such as the one on json.org. It’s small, safe and will not override native JSON implementation if detected.

Points to remember:

  • Plain old eval is unsafe (especially if you don’t trust the source), use a JSON library to protect yourself.
  • Use native JSON when available.
  • Bug other browser vendors to implement native JSON

16 responses

  1. Mike Shaver wrote on ::

    The native JSON API is part of the upcoming 3.1 revision of ECMAScript, so we should see it adopted in browsers pretty quickly. It’s also API compatible with json2.js, as you note, so many many web users will get the performance win without apps needing to update.

    I suspect that the performance advantage for native JSON is even more pronounced on the encoding side, but I don’t have tests to hand to back it up. :)

  2. Bertrand Le Roy wrote on ::

    Great news! I just wanted to point out that IE8 RC1 has been available for a few weeks now (published 1/26), so the “rumors” about a March release can be put to rest :)
    http://www.microsoft.com/windows/internet-explorer/beta/default.aspx
    But maybe you meant the RTW?

  3. betrezel wrote on :

    “What’s the use of native JSON if it’s only available in Firefox? Luckily, IE8 has implemented it in RC1, which is rumored to be released in March. Hopefully other browsers will follow suit too”

    This part is completely misleading. IE8 has implemented Native JSON support since beta 2, which was released in August last year. saying “Hopefully other browsers will follow suit too” implies that IE8 followed Firefox 3.1, which is completely false, as in this case it’s Firefox 3.1 who followed IE8.

    And being intentionally vague in wording makes it sounds like IE8 will only support Native JSON sometime rumored in March this year, when it has already supported Native JSON for over half a year now.

    The correct statement should be :
    What’s the use of native JSON if it’s only available in Firefox? Luckily, IE8 has already implemented it in beta 2, which was released in August last year. Hopefully other browsers will follow Firefox’s step to follow suit too.

  4. Fabien wrote on :

    So, since we’ll have to handle IE6 and IE7 for a long while, what’s the plan to use that new feature while retaining compatibility with old browsers? (Fast on modern browsers, slow but safe on old ones)

    Please, don’t tell me I’ll have to add one more “

  5. Nico wrote on ::

    Apologies for the ignorant question, but what is the feasibility of doing native JSON parsing in a plug-in, effectively allowing older versions of Mozilla to take advantage of this speed/safety improvement?

  6. film indir wrote on ::

    The native JSON API is part of the upcoming 3.1 revision of ECMAScript, so we should see it adopted in browsers pretty quickly. film indir It’s also API compatible with json2.js, as you note, so many many web users will get the performance win without apps needing to update.

    I suspect that the performance advantage for native JSON is even more pronounced on the encoding side, but I don’t have tests to hand to back it up.

  7. articles wrote on ::

    “What’s the use of native JSON if it’s only available in Firefox? Luckily, IE8 has implemented it in RC1, which is rumored to be released in March. Hopefully other browsers will follow suit too”

    This part is completely misleading. IE8 has implemented Native JSON support since beta 2, which was released in August last year. saying “Hopefully other browsers will follow suit too” implies that IE8 followed Firefox 3.1, which is completely false, as in this case it’s Firefox 3.1 who followed IE8. sikiş And being intentionally vague in wording makes it sounds like IE8 will only support Native JSON sometime rumored in March this year, when it has already supported Native JSON for over half a year now.

    The correct statement should be :
    What’s the use of native JSON if it’s only available in Firefox? Luckily, IE8 has already implemented it in beta 2, which was released in August last year. Hopefully other browsers will follow Firefox’s step to follow suit too.

  8. akyaka wrote on ::

    So, since we’ll have to handle IE6 and IE7 for a long while, what’s the plan to use that new feature while retaining compatibility with old browsers? (Fast on modern browsers, slow but safe on old ones)

    Please, don’t tell me I’ll have to add one more “

    and i want to say this;

    Apologies for the ignorant question, but what is the feasibility of doing native JSON parsing in a plug-in, sikiş , effectively allowing older versions of Mozilla to take advantage of this speed/safety improvement?

  9. Patrick wrote on :

    You will always be allowed to use JSON.parse if available by checking if it has been defined by the browser first, just like the way you check for other features such as XMLHTTPRequest which is called something different in IE6:

    if (!JSON) {
    JSON = {};
    }
    if (!JSON.parse) {
    JSON.parse = function(expr) {
    eval(‘(‘+expr+’)’);
    }
    }

  10. Matt wrote on :

    The Graph Server link takes you to a RHEL Apache test page. Did you mean to put http://graphs-stage.mozilla.org/ or did I miss something? Excellent job w/all of this btw.

  11. Joseph R. Justice wrote on :

    At this instant, for me the link at the text “new Graph Server” (http://graphs-stage2.mozilla.org/) in this blog entry goes to a page that’s basically “Hi, you’ve just installed Apache on this machine and this is the default generic home page for the installation”. I don’t know if this is specific to me, or specific to that site, but if it’s the site someone may want to fix it (or fix this link if it’s an incorrect link).

    Hope this is of some use, interest. Thanks for your time.

    Joseph

  12. sikiş izle wrote on ::

    “What’s the use of native JSON if it’s only available in Firefox? Luckily, IE8 has implemented it in RC1, which is rumored to be released in March. Hopefully other browsers will follow suit too”

    This part is completely misleading. IE8 has implemented Native JSON support since beta 2, which was released in August last year. saying “Hopefully other browsers will follow suit too” implies that IE8 followed Firefox 3.1, which is completely false, as in this case it’s Firefox 3.1 who followed IE8.

    And being intentionally vague in wording makes it sounds like IE8 will only support Native JSON sometime rumored in March this year. sikiş izle when it has already supported Native JSON for over half a year now.

    The correct statement should be :
    What’s the use of native JSON if it’s only available in Firefox? Luckily, IE8 has already implemented it in beta 2, which was released in August last year. Hopefully other browsers will follow Firefox’s step to follow suit too.

  13. Timo Reitz wrote on :

    Patrick:

    This will throw an Exception if JSON is not defined:

    if (!JSON) { // Boom!
    JSON = {};
    }

    You should do something like this:
    try{
    var result = JSON.parse(‘{“foo”:”bar”,”fups”:200,”xyz”:[“x”,”y”,”z”]}’)
    // Inspect result
    }
    catch(e){
    // No JSON available, do it yourself
    JSON=function(s){ /* … */ };
    }

    Or inspect this.JSON in a global context, I would recommend that.

  14. Nash Tsai wrote on :

    Can you do async pasring, if JSON string is going to be large, i.e., contains a large number of array elements? Will a good feature if it doesn’t exist, and to be a true ajaj

  15. Json is inSecure wrote on ::

    Personally I hate the JSON framework, its insecure, totally goes against accessability standards, is not search engine friendly. However its always nice to have a new feature in your browser, provided that the feature wont slow down the browser and add a lot of extra crap to the code.

  16. rdoherty wrote on :

    @Json is inSecure

    Actually using native JSON or JSON.js is secure, any exploits are filtered out or ignored.

    JSON is a data interchange format, not meant for people to read, so accessibility is not a concern. It’s also not for rendering pages, so being search engine friendly is not a problem.

    You can compare JSON to XML or CSV files. They are for storing and transmitting data, nothing more. If accessibility and SEO become a concern when using JSON, you’re probably using it wrong.