1

Using the xmltodict (v0.12.0) on python, I have an xml that will get parsed and converted into a json format. For example:

XML:

<test temp="temp" temp2="temp2">This is a test</test>

Will get converted to the following json:

"test": {
    "@temp": "temp",
    "@temp2": "temp2",
    "#text": "This is a test"
}

I have a front end parser that reads JSON objects and converts them into XML. Unfortunately, the tags are required to be shaped in a different way.

What the front end parser expects:

{
    test: {
      "@": {
         temp: "temp",
         temp2: "temp2"
      },
      "#": "This is a test"
    }
}

I feel like this formatting is better served to be modified on Python but I am having a bit of trouble iterating a much larger dictionary, where we don't know how deep an xml would go, and collecting all of the keys that start with "@" and giving that it's own object within the overall tag object. What are some ways I could approach shaping this data?

1 Answers1

0

For anyone who is curious, this is how I ended up solving the issue. Like @furas stated, I decided that recursion was my best bet. I ended up iterating through my original xml data I converted to JSON with the incorrect formatting of attributes, then creating a copy while finding any attribute markers:

def structure_xml(data):
    curr_dict = {}
    for key,value in data.items():
        if isinstance(value, dict):       
            curr_dict[key] = structure_xml(value)
        elif isinstance(value, list):  
            value_list = []
            for val in value:
                if isinstance(val,dict) or isinstance(val,list):
                    value_list.append(structure_xml(val))
            curr_dict[key] = value_list
        else: 
            if '@' in key:
                new_key = key.split("@",1)[1] 
                new_obj = { new_key: value }
                if "@" in curr_dict:
                    curr_dict["@"][new_key] = value 
                else:
                    curr_dict["@"] = new_obj
            elif '#text' in key:
                curr_dict['#'] = data[key]
            else:
                curr_dict[key] = data[key]

     return curr_dict