Hacker News new | ask | show | jobs
Show HN: Xmljson a Swift CLI Tool to Convert XML to JSON (github.com)
15 points by alihilal94 2230 days ago
5 comments

And... it's wrong and busted. The children nodes of an XML node have to be represented as an array in JSON, not as an object. The only things in XML that can be represented as JSON objects (unless your converter is Schema-aware) are attributes, and PIs.

If your converter is aware of XML schemas, then child nodes that have cardinality one or zero-or-one and which have no ordering dependency relative to sibling nodes can be gathered into an object. It's just easier to use arrays for children nodes.

Put it this way: this tool, applied to a document, will butcher it.

For your sample code Python xmltodict gives:

  {
    "bookstore": {
      "book": [
        {
          "@category": "cooking",
          "title": {
            "@lang": "en",
            "#text": "Everyday 1"
          },
          "author": "Giada De Laurentiis",
          "year": "2005",
          "price": "30.00"
        },
        {
          "@category": "web",
          "title": {
            "@lang": "en",
            "#text": "Learning XML"
          },
          "author": "Erik T. Ray",
          "year": "2003",
          "price": "39.95"
        }
      ]
    }
  }
Your code gives:

  [
    {
      "author" : "Giada De Laurentiis",
      "title" : {
        "lang" : "en",
        "text" : "Everyday 1"
      },
      "year" : "2005",
      "category" : "cooking",
      "price" : "30.00"
    },
    {
      "author" : "Erik T. Ray",
      "title" : {
        "lang" : "en",
        "text" : "Learning XML"
      },
      "year" : "2003",
      "category" : "web",
      "price" : "39.95"
    }
  ]
Which one's more accurate?!!
Thanks for your question.

Both are correct, but if you think about it we have a Bookstore with multiple books so putting them in an array of objects makes more sense.. we don't need the root element name. xmltodict just puts extra unnecessary complexity

It loses the tag names in the example. Sometimes the tag names are needed. JsonML preserves them. http://www.jsonml.org/
thanks for notifying me, feel free to open PR if you would like
Not trying to trip you up, but how do you handle namespaces?
You're awesome good bug hunted
Swift CLI tool for converting any XML to JSON format