Why and when to use XML instead of JSON?

Asked

Viewed 8,116 times

18

JSON has at least two advantages over XML:

  1. The Parsing is faster
  2. Occupies less bytes

Still there are people who prefer XML. Is there any reason to prefer XML? Or in what situations it is most suitable (and why)?

  • A doubt... This question can be based on opinion?

  • 4

    I think the question would be better used "Why and when"

4 answers

16


The decision between using XML or JSON is more or less like choosing between a relational database or a Nosql: it all comes down to deciding on a explicit scheme or implicit.

A schematic (schema) is a description of a data set (i.e. metadata). It determines the type of this data, its format, the relationship between them, how they are structured, etc. If this data is for human consumption, the schema doesn’t matter so much - since we have the ability to read and interpret the content in front of us even though it is wrong-structured and "messy". But if the data is for machine consumption (i.e. will be read and manipulated by other programs) then a formal scheme at all times will be necessary - whether it is encoded in meta-data or only agreed.

Just as in a relational BD you need to create the tables, define their columns, their keys and constraints, etc., an XML file can contain the same type of description (in the form of a DTD or Schema) - saying which elements are accepted, which attributes and sub-elements they may have, etc. In this way, it is possible automate the process of verifying whether or not an XML data is valid according to its specification. That is, just as you cannot assign a column that does not exist in a BD, you cannot create an element that does not exist in the schema and the XML is still valid.

On the other hand, it is possible to create an XML without schema - where all content is valid as long as the syntax is correct. It would therefore be the responsibility of the programmer to ensure that this content is generated and consumed according to a logical rule. If it is the same programmer doing both sides, it is easy, because when changing one he will know that he has to change the other (you cannot consume what does not exist, or produce something for anyone). But if it’s a large team - or worse, a set of teams or even separate organizations - it’s harder to track changes and make sure all the subsystems involved handle them properly.

However, if by the particular characteristics of a situation an explicit schema is not even necessary, why not still use XML? In that case, the disadvantages XML makes it a less than ideal solution - the syntax is verbose (every open tag has to be closed), the files become large and therefore difficult to read and write, and the XML processing is harder and slower. In this case, a "lighter" solution is preferable - in the same way as a BD schema-Less will be simpler to use and will perform better than a relational BD trying to handle arbitrary data without structure.

JSON has proved to be an appropriate solution for these cases. It is not the only or necessarily the best (in Wikipedia in English there is a comparing various data serialization formats), but how often the "client" side of communication is a browser - and therefore supports Javascript natively - this additional proximity between the format and the literals of the language itself brought the added advantage of greatly simplifying client code*. I believe this was a decisive factor in consolidating JSON as the "lightweight" preferred alternative to XML. And once he began to receive broad support on most platforms, his ubiquity further increased his advantage.

* I say this in historical terms: in the past we used our own eval Javascript to interpret JSON, but after the XSS threat became evident and well known, it started using functions of its own to make the JS-JSON conversion.

  • 2

    It is interesting to add that XML and JSON should coexist and evolve together for some time, and perhaps acquire less importance if treated in a higher abstraction layer, that of the data model. The specification XSLT 3.0 that should come out this year proposes transformation resources to build data models that treat JSON and XML in an equivalent way, being able to validate and search JSON or XML using Xpath.

  • 2

    There are also initiatives such as JSON Schema and Jsonpath seek to bring to JSON some of the popular facilities that exist in the XML world.

9

JSON:

The JSON object is sometimes used as a "communication bridge" because it is light and fast, unlike the XML that has a sharper structure. The way the JSON object is manipulated is also one of the organizational facilities, making the code cleaner and dedicated only to the data structure. See an example in Actionscript:

var json:Object = {nome: "João", idade: 18, veiculos: ["Twister", "BMW"], parentes: {mae: "Maria", pai: "Joaquim"}};

Not to mention that it is possible to insert an Array directly into an item, as well as another JSON object.

This ease of handling along with speed/lightness is one of the main reasons that makes JSON the perfect tool for data communication with server.

XML:

I believe that XML can function as a "mini-bd", recording some crucial information for some system development, whether local or web.

The data management system is a little more structured, where you can add parameters and values in a given item, as below:

var xml:XML = new XML(
    <root>
        <atualizacao data="06/06/2014"></atualizacao>
        <nome>João</nome>
        <idade>18</idade>
        <veiculos>
            <veiculo>Twister</veiculo>
            <veiculo>BMW</veiculo>
        </veiculos>
        <parentes>
            <pai>Joaquim</pai>
            <mae>Maria<mae>
        <parentes>
        
    </root>
);

Although the structure of an XML is organized and well understood, the interaction with the Web can leave a little more to be desired, because it is a little more complicated to work to rescue all this information, apart from the fact that you cannot adhere to an Array object within a node, creating several nodes with an identical name.

How I would retrieve these two pieces of information:

trace(json["nome"]); //"João"
trace(xml.nome); //"João"

trace(json["veiculos"]); //[Twister, BMW]

trace(xml.veiculos); //<veiculo>Twister</veiculo><veiculo>BMW</veiculo>
trace(xml.veiculos.veiculo[0]); //Twister
trace(xml.veiculos.veiculo[1]); //BMW

trace(xml.atualizacao.@data); //06/06/2014

Yes, there are such differences between them that can influence the end result of your system.

  • 1

    JSON tem uma facilidade incrível de organizar informações What makes him so easy? JSON não é o mais adequado para guardar informações Why XML would be more appropriate?

  • 1

    I edited the answer!

5

XML features several facilities and uses that JSON does not support.

You may have search in it through Xpath, Xquery in addition to being able to validate Schema ( know if you are well formed ) and many other things.

There is room for both technologies, with XML being more robust ( and bureaucratic ) and JSON lighter ( and less controllable? )

3

Depends on the context, my friend. If you are considering choosing from one of them to expose results of an API, for example, it will depend on the default of your API. Typically, Restful Apis tend to use JSON, while web services in the WSDL standard use XML.

XML, by following a markup pattern, will allow you more flexibility, while JSON is a simpler and more direct standard - and currently more accepted in the web context, especially when it comes to single-page Applications.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.