While the other answer is essentially correct (both are generic options for data exchange), it is worth noting that there are a few important differences. XML was built to handle documents. JSON is built to describe objects.
- Character coding, parsing and validation. XML is built to let parsers handle this automatically, JSON not so much.
- Simplicity, compactness. XML simply cannot do this nearly as well as JSON.
Therefore, if you have to write something which will dump the data to a file and the file is transferred sans any meta data (describing mime type, character coding or other conventions), XML may be a superior approach because you can embed the necessary meta data in the data using appropriate declarations (and namespaces). This is especially important when it comes to "documents": JSON simply does not have the primitives to describe locale very well and there is no sane standard way to do it that will be understood by all parsers. Therefore if someone did something incredibly silly like converting your UTF-8 coded JSON string to Shift-JIS, well good luck getting any parser to understand that in a generic fashion. XML solves that (and it also provides for language support).
On the other hand if all you ever want to do is exchange a bunch of objects in a highly controlled setting (i.e. character coding, language etc. are all well defined parameters) and you therefore do not have to worry about arbitrary weirdness coming your way -- then JSON offers a much more compact serialisation format, which is also (probably) easier to read for most programmers. Finally JSON is particularly amenable to web applications, because it happens to be valid JavaScript all by itself. While treating JSON as part of your JavaScript code using something like eval
, is not a good security practice for consuming arbitrary JSON; it can help to simplify the "getting up and running" stage of any front end for a web application which you do have full control over (all you would need to do is `eval' it, though again for code which has to work with arbitrary JSON this is a terrible idea because that could expose you to security vulnerabilities of other sites as well as your own).