Search code examples
xmlajaxjsonxmlhttprequest

What are the advantages and disadvantages of json vs xml for ajax requests?


What are the advantages and disadvantages of json vs xml for ajax requests? Is there a difference in performance? i.e. are browsers able to process one format faster than the other?


Solution

  • In summary, JSON (which can be thought of a subset of JavaScript) is a lot leaner than XML. This has several positive side-effects

    • JSON is smaller than corresponding XML
    • JSON is faster, i.e. simpler syntax -> easier parsing (faster parsing)

    In my original answer to this question, my view of JSON was that of JavaScript, I considered it to be a close relative. But JSON is something independent and JSON.org does a great job of describing JSON. It's also provides a compatibility library for JavaScript that adds support for JSON.parse and JSON.stringify when not supported by browsers.

    While eval at the time (mid 2009) was used to evaluate JavaScript, it could also evaluate JSON, i.e. parse JSON, but it was considered unsafe, as it did allow arbitrary JavaScript to execute in its stead.

    JSON just happens to be a very good fit for browsers and a natural way to evolve the platform due to its close relationship with JavaScript.

    While XML might be considered to have better rigor due to the fact that you can type it, it is also those things that make it a lot slower (it is also a bit verbose in my opinion). But if this is something you really want, you should use it, XML is equally ubiquitous.

    I will not go into a debate over dynamic or statically typed, but I will say this. It's really easy to add stuff on top of schema-free data and there are plenty of ways to do validation, regardless of schema or no schema.