Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xml to json mapping challenge

At first glance, I thought using xml data in javascript would be as simple as finding an xml-to-json library and turning my xml into a javascript object tree.

Now, however, I'm realizing that it's possible to create structures in xml that don't map directly to json.

Specifically, this:

<parentNode>
    <fooNode>data1</fooNode>
    <barNode>data2</barNode>
    <fooNode>data3</fooNode>
</parentNode>

The xml-to-json tools I've found convert the previous to something like this:

{
parentnode:{
    foonode:[
        'data1',
        'data3'
    ],
    barnode:'data2'
}

}

in which, the order of the child nodes has been changed. I need to preserve the order of my child nodes. Anyone have any solution that's more elegant than

a) abandoning the idea of automatic conversion and just designing my own javascript object structure and writing code to handle this specific xml schema

or

b) abandoning the idea of any conversion at all, and leaving my xml data as an xml document which I'll then traverse.

like image 314
morgancodes Avatar asked May 12 '09 16:05

morgancodes


2 Answers

There are established mappings from XML to JSON with limitations (see Converting Between XML and JSON) and mappings from JSON to XML (see JSONx as defined here and conversion rules by IBM). A mapping from XML to JSON that preserves order, however, has not been defined yet. To fully capture all aspects of XML, one should express the XML Infoset in JSON. if you only care about XML elements (no processing instructions, etc.), I'd choose this structure:

[
  "parentNode",
  { } /* attributes */
  [ 
    [ "fooNode", { }, [ "data1" ] ]
    [ "fooNode", { }, [ "data2" ] ]
    [ "fooNode", { }, [ "data3" ] ]
  ]
]

I implemented the same mapping as mapping between XML and Perl data structures that are just like JSON with XML::Struct. The structure further corresponds to the abstract data model of MicroXML, a simplified subset of XML.

like image 136
Jakob Avatar answered Sep 21 '22 16:09

Jakob


If you need the same element name often and you care about ordering it might be better to stay with XML. What benefits do you expect from using JSON?

like image 28
Norbert Hartl Avatar answered Sep 20 '22 16:09

Norbert Hartl