Python: serialize a JSON foam object

I am making calls to SOAP API using suds, which returns data as objects, not raw XML. I want to keep a copy of the raw response in addition to what I am parsing, the end goal is to store as JSON (I am currently using TinyDB for testing).

The overall flow looks like this:

  • Get the original answer
  • Create a raw response request using the script below
  • Analysis response elements for later use
  • Serialize everything to JSON and store in TinyDB

My script to convert suds object to dict:

def makeDict(response):
    out = {}
    for k, v in asdict(response).iteritems():
        if hasattr(v, '__keylist__'):
            out[k] = makeDict(v)
        elif isinstance(v, list):
            out[k] = []
            for item in v:
                if hasattr(item, '__keylist__'):
                    out[k].append(makeDict(item))
                else:
                    out[k].append(item)
        else:
            out[k] = v
    return out

      

However, sometimes when I run makeDict(object)

and try to serialize to JSON, I get a type error like below:

  File "C:\Python27\Lib\json\encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: (Date){
   Day = 7
   Month = 8
   Year = 2004
 } is not JSON serializable

      

This error is throwing me back because:

  • I know this object Date

    appears in other entries that do not throw errors during serialization
  • type (Date.Day) is int and field name is string

Does anyone have an idea what is going on here? It looks like it is trying to serialize the raw object, but whatever I put into TinyDB is already executing viamakeDict

+3


source to share


1 answer


I suppose I'll answer my own question rather than delete it in case anyone else comes across this issue.



The foam object sometimes contains a list, which in turn contains other suds objects. The function makeDict()

does not necessarily go to the deepest nesting level, so it sometimes returns a dict containing a suds object that cannot be serialized.

+2


source







All Articles