Arrays natural translation possibility
Let's try the following XML:
<data>
<totalrows>2</totalrows>
<rows>
<row>
<prop1>A</prop1>
<prop2>B</prop2>
<prop3>C</prop3>
</row>
<row>
<prop1>D</prop1>
<prop2>E</prop2>
<prop3>F</prop3>
</row>
</rows>
</data>
x2js converts it to this JSON:
{
"data": {
"totalrows": "2",
"rows": {
"row": [
{
"prop1": "A",
"prop2": "B",
"prop3": "C"
},
{
"prop1": "D",
"prop2": "E",
"prop3": "F"
}
]
}
}
}
Look at <rows> element. Basically it's a container for collection of <row> elements. In other words, <rows> should naturally be translated to "rows":[...], where each <row> should be an object (anonymous, because of javascript nature):
{
"data": {
"totalrows": "2",
"rows": [
{
"prop1": "A",
"prop2": "B",
"prop3": "C"
},
{
"prop1": "D",
"prop2": "E",
"prop3": "F"
}
]
}
}
But instead, x2js translates <rows> to an object with the only one property <row> which is array.
When I'm trying to use this config to translate <rows> to array:
{ arrayAccessFormPaths : ["data.rows"] }
then I'm getting this result:
{
"data": {
"totalrows": "2",
"rows": [
{
"row": [
{
"prop1": "A",
"prop2": "B",
"prop3": "C"
},
{
"prop1": "D",
"prop2": "E",
"prop3": "F"
}
]
}
]
}
}
which makes "rows" an array containing one object with (again) the only one "row" element which in turn is array of actual objects. And this doesn't make much sense.
Is there a way to get a natural array translation in x2js? If we care about array's elements names, it's possible to add an accessor to the array'ed object, like this:
{
__object_name: "row",
"prop1": "A",
"prop2": "B",
"prop3": "C"
}
Unfortunately, it's not possible to implement in general and you're trying to change the current direct and simple translation behaviour.
Let me explain: If you try to describe your example with XSD you will get something like:
<element name="rows">
<complexType>
<complexContent>
<element name="row" maxOccurs="unbounded"/>
</complexContent>
</complexType>
</element>
It's not just only about the name of parent (rows). It could contain attributes, namespaces, text content, other elements (because x2js don't have all information about XSD it's generally indefinite runtime).
This is a nature of XML and what you're asking is a workaround for some cases. I think this could be implemented like additional option for the specific paths/elements.
I'm planning to implement custom transforming functions and it'll be possible to register your own custom transformer for the specific paths (like array forms and datetimes).