Parsing Suds SOAP complex data type into Python dict

前端 未结 6 1836
生来不讨喜
生来不讨喜 2020-12-31 23:24

I have some data coming from a SOAP API using Suds which I need to parse in my Python script. Before I go off and write a parser (ther

6条回答
  •  甜味超标
    2020-12-31 23:30

    The checkaayush's answer is not recursive so, it does not consider the nested objects.

    Based on aGuegu Answer i did some changes to solve an issue when the suds object has dicts inside lists.

    It works!

    
    from suds.sudsobject import asdict
    
    def recursive_asdict(d):
        """Convert Suds object into serializable format."""
        out = {}
        for k, v in asdict(d).items():
            if hasattr(v, '__keylist__'):
                out[k] = recursive_asdict(v)
            elif isinstance(v, list):
                out[k] = []
                for item in v:
                    if hasattr(item, '__keylist__'):
                        out[k].append(recursive_asdict(item))
                    elif not isinstance(item, list):
                        out[k] = item
                    else:
                        out[k].append(item)
            else:
                out[k] = v
        return out
    

提交回复
热议问题