Downside to serialising JSON API as XML


#1

The HAL format has a very brief mention of an XML format. https://gist.github.com/mikekelly/994942 is actually the only example I could find, but I get the impression that it is not a one to one mapping with JSON.

What is the downside to simply converting JSON to XML should a JSON API client prefer it? Is there some hidden danger or JSON structures that can’t be replicated as XML? Or is there some other reason why you wouldn’t want to expose JSON API as XML?


#2

A few things. First of all, there’s no canonical way to convert JSON data to XML, because JSON and XML have different metamodels. (E.g. XML has attributes and namespaces; JSON doesn’t.) So, while concepts from JSON API (largely) make sense in XML, there’s no “best” way to serialize them. E.g., imagine a resource object that looks like this in JSON API:

{
  "type": "people",
   "id": "1",
   "attributes": {
     "first-name": "John"
   }
}

In XML, should that look like:

<resource type="people" id="1">
   <attributes>
      <attribute name="first-name" value="John" />
   </attributes>
</resource>

Or:

<people id="1">
  <first-name>John</first-name>
</people>

Or something in between?

More importantly, though, the whole point of JSON API is to have a common convention that enables generic clients etc. And that convention is only defined (by the spec) for JSON. So using XML wouldn’t work with any of the existing tooling, and would lead to fragmentation that’s antithetical to interoperability.

So, bottom line: if you absolutely need to support XML, and you find the concepts from the JSON API spec (like that of a resource object or a compound document) useful, feel free to use those concepts to create an XML serialization. But understand that that XML serialization will be non-standard, so you’ll be forfeiting most of benefits of using JSON API.

(Also, if you do serialize XML, make sure you’re not using the application/vnd.api+json media type, of course.)

For context, here’s what Mark Nottingham has to say on the topic:

###JSON or XML: Just Decide

Starting with either of JSON and XML is going to create an abomination in the other format; a JSON-based model won’t use all of the power of XML and will feel “alien” to XML-friendly developers, and an XML-based model is going to be really verbose, ugly and non-JSONic as JSON.

This is because the underlying metamodels are fundamentally different. JSON is based upon a handful of common programming language data structures, and is inherently simple. XML, on the other hand, is based upon the Infoset, which is legendarily complex and hard to map to those data structures.

From https://www.mnot.net/blog/2012/04/13/json_or_xml_just_decide