3

I've been using the python package xmltodict very successfully to parse my xml string into a python dictionary.

However, I have the following issue:

<child>
  <episode>["a","b"]</episode>
</child>

parses as:

 { 
  child: {
    episode: ["a","b"]
    }
 }

whereas:

<child>
  <episode>["a","b"]</episode>
  <episode>["c","d"]</episode>
</child` 

parses as:

{ child: 
   {
    episode: [
     ["a","b"],
     ["c","d"]
     ]
    }
 }

which means that an code I write is going to give me different results depending on which child observation I'm looking at.

What I'd like is a way to specify to parse the episode always as an array - similarly to this .Net package. What would be the best way (or a way) of doing this in Python?

user988029
  • 75
  • 1
  • 8

1 Answers1

2

Try a flatten function on the "episodes" key?

def flatten(it):
    res = []
    for item in it:
        if not isinstance(item, list):
            res.append(item)
            continue
        res.extend(item)
    return res
knight
  • 435
  • 5
  • 18