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 (there is more than just this one to do):
1) Does anyone recognise what this is? It's the standard complex object datatype as returned by Suds
(documentation). Should have spotted that.
2) If so, is there an existing library that I can use to convert it to a Python dictionary? How do I parse this object into a Python dict? It seems I can pass a dictionary to Suds but can't see an easy way of getting one back out.
(ArrayOfBalance){
Balance[] =
(Balance){
Amount = 0.0
Currency = "EUR"
},
(Balance){
Amount = 0.0
Currency = "USD"
},
(Balance){
Amount = 0.0
Currency = "GBP"
},
}
The right answer, as is often the case, is in the docs. The bits in (brackets) are objects which can contain other objects or types.
In this case we have an
ArrayOfBalance
object which contains a list ofBalance
types, each of which has the attributes ofAmount
andCurrency
.These can all be referred to using
.
notation so the following one-liner does the trick.There is a class method called
dict
insuds.client.Client
class which takes asudsobject
as input and returns a Pythondict
as output. Check it out here: Official Suds DocumentationThe resulting snippet becomes as elegant as this:
You might also want to check out
items
class method (link) in the same class which extracts items from suds_object similar toitems
method ondict
.Found one solution:
If subs are just nested dict and list, it should work.
I was encountering a similar problem and had to read a suds response. Suds response will be returned as a tuple consisting of objects. len(response) will show you the number of objects contained in the suds response tuple. In order to access the first object we need to give
response[0]
.In IDLE if you type
>>>print response[0]
followed by a period '.' symbol you will get a popup showing the various objects that can be accessed from this level.Example: if you type
response[0]
. it will bring a popup and show the Balance object so the command would now becomeresponse[0].Balance
.You can follow the same approach to get the list of objects under the subsequent levels
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!
You can cast the object to
dict()
, but you still get the complex data type used by suds. So here are some helpful functions that I wrote just for the occasion:If there is an easier way, I would love to hear about it.