sanand0 / xmljson

xmlsjon converts XML into Python dictionary structures (trees, like in JSON) and vice-versa.
MIT License
122 stars 33 forks source link

Single element array #26

Open numjcp opened 7 years ago

numjcp commented 7 years ago

Hello, great job with this python module !!

However, i came across a simple problem. Say i wish to convert the following xml to json along yahoo convention

i get {"commandes": {"commande": [{}, {}]}} which is ok for me.

But if i convert the same xml with only one object

i get {"commandes": {"commande": {}}} which is Good but not the behavior I expect. I'd like to get the single element within an array as if several objects where present. That is to say : {"commandes": {"commande": [{}]}}

Thanks

numjcp commented 7 years ago

<commandes><commande/><commande/></commandes> and <commandes><commande/></commandes>

are the source xml's

numjcp commented 7 years ago

Here's a quick fix at first glance.

(How) would you like to integrate this behaviour ?

def data(self, root):
        '''Convert etree.Element into a dictionary'''
        value = self.dict()
        children = [node for node in root if isinstance(node.tag, basestring)]
        for attr, attrval in root.attrib.items():
            attr = attr if self.attr_prefix is None else self.attr_prefix + attr
            value[attr] = self._fromstring(attrval)
        if root.text and self.text_content is not None:
            text = root.text.strip()
            if text:
                if self.simple_text and len(children) == len(root.attrib) == 0:
                    value = self._fromstring(text)
                else:
                    value[self.text_content] = self._fromstring(text)
        count = Counter(child.tag for child in children)
        for child in children:
            #if count[child.tag] == 1:
            #    value.update(self.data(child))
            #else:
            result = value.setdefault(child.tag, self.list())
            result += self.data(child).values()
        return self.dict([(root.tag, value)])
wyleung commented 6 years ago

This is exactly the same issue i'm facing.

I think, this problem is more related to the source file or the need for a xsd where the expected elements are described

javadev commented 5 years ago
{
   "commandes": {
      "commande": [
         {
         },
         {
         }
      ]
   }
} 

may be converted to xml

<?xml version="1.0" encoding="UTF-8"?>
<commandes>
  <commande></commande>
  <commande></commande>
</commandes>
DanielKaupp commented 4 years ago

I'm having the same issue with the Parker Convention -> No problem here, as how I found out, Parker is specified that way. There is though another convention 'Spark' that is similar to Parker, but treats single entries as lists.

http://wiki.open311.org/JSON_and_XML_Conversion/

Perhaps someone could also provide 'Spark' Convention as an extension to xmljson?