David Pollak was right about XML and JSON

David Pollak was right about XML and JSON, but perhaps in a different way. XML cannot be converted to (clean) JSON.

Suppose we have a shopping cart in XML which we want to convert to JSON:

<cart>
  <items>
    <item><name>one</name></item>
    <item><name>two</name></item>
  </items>
</cart>

One representation in JSON would be (cart could be omitted):

{ cart: { "items": [ { "name": "one" }, {"name": "two"} ] } }

We convert a list of nodes with the same name to a JSON array, xml2json-xslt does this for example. What happens if we only have one item in our shopping cart?

<cart>
  <items>
    <item><name>one</name></item>
  </items>
</cart>

Then our converter cannot detect that items is a list and will convert the XML to:

{ cart: { "items": { "name": "one" } } }

which is semantically something completely different. And very unpleasent for the receiver of our JSON code, because sometimes he gets an array and sometimes an object.

One way to solve the problem is to annotate the XML (looks ugly but works):

<cart>
  <items type="list">
    <item><name>one</name></item>
  </items>
</cart>

and adding an additional condition to the XSLT

or ../@type[.='list']]

or namespacing (doesn't work yet, we get lots of namespaces and misuse XML namespaces) ?

<cart>
  <list:items>
    <item><name>one</name></item>
  </list:items>
</cart>

So David was right, I'm not sure he new why 😉

Thanks for listening.

Stephan Schmidt Administrator
CTO Coach , svese
Stephan is a CTO coach. He has been a coder since the early 80s, has founded several startups and worked in small and large companies as CTO. After he sold his latest startup he took up CTO coaching. He can be found on LinkedIn or follow him in Twitter.
follow me