xmljson

How would I express XML tag attributes in JSON?


I am designing an API for my webapp.

I was thinking to support only JSON responses (not XML) because more streamlined.

But I have just bumped to this XML:

<folders>
    <folder id="123" private="0" archived="0" order="1">Shopping</folder>
</folders>

and I was wondering how the corresponding JSON would be. I have the feeling, in this case, XML would be more compact.


Solution

  • Perhaps:

    {
      "folders": [
        { "id":123, "private":0, "archived":0, "order":1, "title":"Shopping" },
        ...
      ]
    }
    

    Because there is not an exact correspondence between XML and JSON, you are free (e.g. have to define) how the two data-structures map. For instance, in the above, the "folder" element is implicit in the nested objects in the "folders" array.

    This could be expanded as in:

    "folders": [{"folder": { .... }]
    

    Etc, but there is still the problem of not being able to capture content+attributes as consistently as XML. In any case, your data-structure -> JSON|XML serializer likely works in a particular way (and please, please, use a library, not "hand-rolled" JSON-string-munging). That is; the format of the XML and JSON should be uniformly dictated (somehow) by the data-structure for transmission.