When to prefer JSON over XML?

JavascriptJqueryXmlJson

Javascript Problem Overview


My requirement is just to display a set of values retrieved from database on a spread. I am using jquery.

Javascript Solutions


Solution 1 - Javascript

Favor XML over JSON when any of these is true:

  • You need message validation
  • You're using XSLT
  • Your messages include a lot of marked-up text
  • You need to interoperate with environments that don't support JSON

Favor JSON over XML when all of these are true:

  • Messages don't need to be validated, or validating their deserialization is simple
  • You're not transforming messages, or transforming their deserialization is simple
  • Your messages are mostly data, not marked-up text
  • The messaging endpoints have good JSON tools

Solution 2 - Javascript

I use JSON unless I'm required to use XML. It's simpler to understand, and (because it requires less configuration overhead) it's easier to program for reading and writing if the libraries are available in your context, and they're pretty ubiquitous now.

When Amazon first exposed their catalogs as a web service, they offered both JSON and XML. Something like 90% of the implementers chose JSON.

Solution 3 - Javascript

Considering your specific case where you're already doing javascript on the client side, I'd go with JSON for these reasons:

  • Since JSON is native to javascript you'd have to write less code on the client side - Just eval() (or, better yet, JSON.parse()) the JSON string and get an object you can use.

  • At the same time evaluating JSON on the client-side will be more efficient, and therefore faster.

  • JSON serialization produces shorter strings than XML. Using JSON will reduce the amount of data running across the wire and improve performance in that respect.

Here's some further reading: http://www.subbu.org/blog/2006/08/json-vs-xml

Solution 4 - Javascript

Some other things that I have run into in the XML vs JSON relm:

JSON is very good for

  • name/value pairs
  • nesting those pairs

Which means it tends to like an array or nested array. However JSON is missing both

  • attributes
  • namespacing

So if you were to combine two or more JSON services there could be potential namespace conflicts. That being said JSON can be used for about 90% of the same things XML can be used for when exchanging data in my experience.

Solution 5 - Javascript

Usually JSON is more compact, and faster to parse.

Prefer XML if:

  • You need to process the data on the client, and you can leverage XSL for that. Chances are the XML + XSL chain will work faster than JSON + JavaScript especially for big chunks of data.
    • One good case is to convert the data into an HTML snippet.
  • Various legacy cases:
    • There is an existing XML service, and it is a hassle to rewrite it with JSON for some reasons.
    • You have to post this data back as XML after some light processing using user's input.

One important case of (almost) XML: try to detect when sending HTML snippets is more beneficial than sending raw data. http://en.wikipedia.org/wiki/Ahah">AHAH</a> can do wonders in simple applications, yet frequently overlooked. Usually this style assumes that a server sends HTML snippets that will be inlined in the web page without processing.

Usually in AHAH cases CSS is being leveraged to the max to massage snippets visually and implementing simple conditionals like hiding/showing relevant parts of the snippet using user-specific or application-specific settings.

Solution 6 - Javascript

JSON is always preferable in terms of the processing the client browser has to do for parsing the data. Also, JSON is light weight data exchange format.

XML parsing always consumes lot of browser resources and should be avoided as much as we can unless otherwise required.

Solution 7 - Javascript

JSON is easy and faster to parse. XML is a little more difficult to parse, and is slower to parse and transfer (in most cases).

Since you're using jQuery, I suggest using JSON: jQuery can retreive JSON data and convert it into a Javascript object automatically. In fact, you can convert JSON data into a Javascript object using eval. XML would have to be transversed manually by you (I don't know how this works in Javascript, but it's difficult/more annoying in most languages I've used XML libraries with).

Solution 8 - Javascript

I have a blog post on the subject detailing the history of web protocols (i.e. SOAP, XML, JSON, REST, POX, etc) providing a summary as well as some advantages and disadvantages of each: http://www.servicestack.net/mythz_blog/?p=154

I actually think you can draw many similarities between XML and JSON by comparing the differences between dynamic (JSON) and static (XML) languages.

Basically XML is a stricter, more rigid serialization format that can be optionally be verified with an accompanying schema (which is either an XSD or DTD). XSD's are quite elaborate and allows you to describe many different types e.g. Dates, Times, Enumerations, User Defined Types and even Type inheritance, etc. SOAP effectively builds on top of the XML feature-set providing a standardized way to describe your web services (e.g. types and operations) through a WSDL. The verbosity and complexity of the WSDL spec means that it can be more tedious to develop with but at the same time there is a lot more tooling available to you and most modern languages provide automated tools to generate your client proxies taking some some of the burden off when trying to interoperate with external services. (Although at the same time I find generated proxies a burden themselves when dealing with frequently changing web services).

I would still recommend using XML for your web services if you have a well defined 'enterprise service' that is not subject to frequent change or your web service needs to be accessed from many different languages.

For all its benefits XML comes with downsides as well. It relies on namespaces in order to provide a typed extensible format and enables you to specify attributes and elements within the same document. Having different namespaces within the one document means a lot of the time when using a Xml Parser to extract data, you will also need to provide the namespace of each element you want to retrieve/traverse. It also extrapolates the payload making it more verbose than it needs to be. Having the option to output attributes as well as elements means your classes do not map nicely to an XML document. These features alone make it a poor programmatic fit for most languages making it more tedious and cumbersome to work with. Microsoft has recognized and simplified this somewhat with in their DataContract serializer by doing away with XML attributes and just having the properties of your class map to Xml elements only.

JSON on the other hand is the complete opposite to XML in many ways as it is very loosely-typed and only has simple support for basic types: Number, Bool, string, Objects and Arrays. Everything else essentially has to fit in a string. This is not great when trying to communicate across language boundaries as you will need to adhere to some out-of-band non-standard specification if you want to support more specific types. On the upside its limited feature-set makes a good programmatic fit to most languages - and is perfectly suited for JavaScript as a JSON string can be eval'ed directly into JavaScript object.

Size and Performance

I have some northwind database benchmarks available comparing the size and speed between Microsofts XML and JSON implementations. Basically XML is more than 2x the size of JSON but at the same time it looks as if Microsoft put in a lot of effort in optimizing their XML DataContractSerializer as it is more than 30% faster than their JSON one. It seems that you have to make trade-off between size and peformance. Not happy with this fact, I decided to write my own fast JsonSerializer which is now 2.6x faster then MS's XML one - so best of both worlds :).

Solution 9 - Javascript

I'd choose XML over JSON if I need to validate the chunk of incoming data, because XML nativly supports this through XSD.

Solution 10 - Javascript

from JSON - the last feet

> When you go down the JSON route, you > run into the same issues that XML > faced 10 years ago: > > > > > > Mixing data from two different sources > into one JSON packet can cause element > labels to bump into each other. Mix up > a packing slip and an invoice, and > suddenly the From address may mean > something quite different. That’s why > XML has namespaces. > > > > > Converting between different JSON > structures would require writing > mundane code. A more declarative way > to map data would make the job easier. > That’s why XML has XSLT. > > > Describing a JSON packet’s > structure—its fields, data types, > etc.—is necessary in order for people > to hook into your services. It’s > essential to have a metadata language > for this. That’s why XML has Schemas. > > > > > Carrying on two simultaneous > client-server conversations takes > care. If you ask the server two > questions and get one answer back, how > do you know what question it answers? > That’s why XML has WS-Correlation.

Solution 11 - Javascript

JSON is the native encoding for javascript. It should be much faster and easier to work with.

Solution 12 - Javascript

From the first line at http://json.org/xml.html > Extensible Markup Language (XML) is a text format derived from Standard Generalized Markup Language (SGML). Compared to SGML, XML is simple. HyperText Markup Language (HTML), by comparison, is even simpler. Even so, a good reference book on HTML is an inch thick. This is because the formatting and structuring of documents is a complicated business. . . .

Clearly JSON is faster, but it's even more clear that it is hard to read. Use JSON for speed, use XML if there will be human-interaction and you can sacrifice the speed.

Solution 13 - Javascript

I use JSON for any kind of configuration, data interchange or messaging. I use XML only if I have to for other reasons or to semantically mark up document-like data.

Solution 14 - Javascript

Both XML and JSON are supported by Microsoft. XML literals were the new cool feature in VB 9. In the upcoming version of ASP.NET 4.0 JSON is a must to leverage the power of client side templating.

From the question you have asked it seems JSON might be the choice for you as it is easy to process on client side with or without jQuery.

Solution 15 - Javascript

Using JSON

  • If the data is to be consumed by JavaScript in the browser.
  • Data model is simple and not complex(too many composite objects).

Using XML

  • Mostly in an SOA kind of environment where you are integrating several services on heterogeneous platforms and technologies.
  • SOAP has an advantage that it can be transmitted across different protocols other then HTTP.
  • Easy to use in data model transformation tool like XSLT,XSL-FO etc.
  • Lot of Database support to store/query(XQuery) XML data.
  • XML is a very mature data format so you would find plenty of tools to support any use case that you can think of.

Solution 16 - Javascript

I found this article at digital bazaar really interesting.

Some portions from the article are quoted below.

About JSON pros:

> If all you want to pass around are atomic values or lists or hashes of > atomic values, JSON has many of the advantages of XML: it’s > straightforwardly usable over the Internet, supports a wide variety of > applications, it’s easy to write programs to process JSON, it has few > optional features, it’s human-legible and reasonably clear, its design > is formal and concise, JSON documents are easy to create, and it uses > Unicode. ...

About XML pros:

> XML deals remarkably well with the full richness of unstructured > data. I’m not worried about the future of XML at all even if its death > is gleefully celebrated by a cadre of web API designers. > > And I can’t resist tucking an "I told you so!" token away in my > desk. I look forward to seeing what the JSON folks do when they are > asked to develop richer APIs. When they want to exchange less well > strucured data, will they shoehorn it into JSON? I see occasional > mentions of a schema language for JSON, will other languages follow? >...

Solution 17 - Javascript

Quick rules:

  • JSON: program-to-program data format
  • YAML (JSON superset): human-to-program data format
  • XML: document markup format

Explanation:

JSON's sole role is to serialize object-oriented data using the data types common to most programming languages: lists, hashes, and scalars, and for that purpose it really can't be beaten or improved upon. To wit "JSON has no version number [as] no revisions to the JSON grammar are anticipated". - Douglas Crockford (Can't beat that as a sign that you do your job perfectly)

XML was once sold as a data inter-change format, but consider the two most common use cases: Asynchronous client-server communication (AJAX) - JSON has pretty much replaced XML entirely (The X should really be a J), and web services: JSON has made XML a redundant alternative.

The other thing XML was widely used for was human writable/readable(?) data files for programs, but here too you have a more concise, more program-friendly, more human-friendly format in YAML, a JSON superset.

So for data representation, JSON beats XML across the board. What's left for XML then? Mixed-content document representation, which is what it was intended for.

Solution 18 - Javascript

Most newer web technologies work using JSON, so definitively a good reason for using JSON. A great advantage is that in XML you can represent in multiple different ways the same information, which in JSON is more straightforward.

Also JSON IMHO is much clearer than XML, which makes it for me a clear advantage. And if you are working with .NET, Json.NET is a clear winner to help you work with JSON.

Solution 19 - Javascript

I am seeing a bit of bias dogma here. It appears that answers for this are over simplified for xml and coming from the context of Web Development only (which makes sense for the question), so I figured id offer some additional insight just in case some one crosses this and needs an answer for data serialization in other contexts.

Here are the hard and fast rules:

XML is definitely, not arguably, more powerful. So use it when your data model is complicated enough to need the following features:

  1. Support for Namespaces
  2. Support for Object Orientation ie inheritance/polymorphism
  3. Support for inclusion and extensibility for complex type reuse.
  4. Support needed for a reliable, mature and complete Schema Validation system.
    • the w3c Schema Validation system is vastly more capable to JSON Schema and has more literature to learn it.
  5. Support for mixed content document data modelling up AND record like data modelling.

JSON is simpler to learn, understand and use. So use it when you dont have time to learn XML and dont have a need for any of the above features. Its also more lightweight on the wire, if that matters for your use case.

TL:DR, XML can do everything json can do, but is heavier. The reverse is simply not true. Yes Json is simpler and therefor used more, but that does not mean it can supplant XML. In the case I was up against this year, 2020, json didnt make the cut for our use case, we literally needed XML. I can talk about that more if needed. Cheers and good luck.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsaregoView Question on Stackoverflow
Solution 1 - JavascriptRobert RossneyView Answer on Stackoverflow
Solution 2 - JavascriptdkretzView Answer on Stackoverflow
Solution 3 - JavascripturigView Answer on Stackoverflow
Solution 4 - JavascriptnullView Answer on Stackoverflow
Solution 5 - JavascriptEugene LazutkinView Answer on Stackoverflow
Solution 6 - JavascriptTejasviView Answer on Stackoverflow
Solution 7 - JavascriptstragerView Answer on Stackoverflow
Solution 8 - JavascriptmythzView Answer on Stackoverflow
Solution 9 - JavascriptlowgliderView Answer on Stackoverflow
Solution 10 - JavascriptÖzgürView Answer on Stackoverflow
Solution 11 - JavascriptDustinView Answer on Stackoverflow
Solution 12 - Javascriptuser3389057View Answer on Stackoverflow
Solution 13 - JavascriptLawrence DolView Answer on Stackoverflow
Solution 14 - JavascriptMoizNgpView Answer on Stackoverflow
Solution 15 - JavascriptRohitdevView Answer on Stackoverflow
Solution 16 - JavascriptChristian VielmaView Answer on Stackoverflow
Solution 17 - JavascriptYarinView Answer on Stackoverflow
Solution 18 - JavascriptxmoreraView Answer on Stackoverflow
Solution 19 - JavascriptcsevierView Answer on Stackoverflow