A job interview JavaScript task – parsing XML to JSON

Some time ago I was presented with the following task: create in JSON a list of all the 2nd level nodes from an XML input and display the number of children for each such node. It sounds simple but it’s trickier than instantiating the DOMParser and then using JSON.parse (read about them at MDN).

If your input is:

<a>
  <b>
    <d></d>
  </b>
  <c>
    <d></d>
  </c>
</a>

Then there are two 2nd level nodes – <d></d> and <d></d>. These nodes have the same names but are different nodes of different parents and might have different numbers of children.

However if you use JSON.parse('{"d" : "0", "d" : "0"}'); then the result is Object { d="0"}. That’s just not correct. Duplicate keys are not disallowed in JSON (there’s a reference to the spec there). A JSON validator says the same. The duplicated keys are valid, although there’s a warning raised.

Obviously not everything that’s not forbidden should be done. It’s crucial to have a common understanding (and a way of handling) of such edge cases. I thought that this was the catch of this task and solved it by putting the JSON together by myself and writing a comment.

As it often is the reviewer overlooked/disregarded the comment and claimed that I made an error outputting duplicated keys anyway :).