Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transforming string output to JSON

Tags:

python

json

I'm getting some data from an external system (Salesforce Marketing Cloud) over API and I'm getting the data back in the format below:

Results: [(List){
   Client =
      (ClientID){
         ID = 113903
      }
   PartnerKey = None
   CreatedDate = 2013-07-29 04:43:32.000073
   ModifiedDate = 2013-07-29 04:43:32.000073
   ID = 1966872
   ObjectID = None
   CustomerKey = "343431CD-031D-43C7-981F-51B778A5A47F"
   ListName = "PythonSDKList"
   Category = 578615
   Type = "Private"
   Description = "This list was created with the PythonSDK"
   ListClassification = "ExactTargetList"
 }]

It's tantalisingly close to JSON, I'd like to format it like a JSON file so that I can import it into our database. Any ideas of how I can do this?

Thanks

like image 862
Hew Ingram Avatar asked Oct 30 '22 20:10

Hew Ingram


2 Answers

It looks like an object called suds which is already in Python. The Fuel-SDK uses it.

The suds object already did that for you. Just call the attribute you are looking for.


However, if you want it as a dict, attached is the common function for that:

from suds.sudsobject import asdict

def recursive_asdict(d):
    out = {}
    for k, v in asdict(d).iteritems():
        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))
                else:
                    out[k].append(item)
        else:
            out[k] = v
    return out

def suds_to_json(data):
    return json.dumps(recursive_asdict(data))

The first one will translate it to dict and the second one to proper json.

Some useful links: https://fedorahosted.org/suds/wiki/Documentation

like image 65
DarkDiamonD Avatar answered Nov 15 '22 05:11

DarkDiamonD


To convert your array, you could use var jsonString = JSON.stringify(yourArray);

like image 39
cbroomhead Avatar answered Nov 15 '22 06:11

cbroomhead