加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 将字符串输出转换为JSON

发布时间:2020-12-16 22:44:55 所属栏目:Python 来源:网络整理
导读:我通过API从外部系统(Salesforce Marketing Cloud)获取一些数据,我将以下面的格式获取数据: Results: [(List){ Client = (ClientID){ ID = 113903 } PartnerKey = None CreatedDate = 2013-07-29 04:43:32.000073 ModifiedDate = 2013-07-29 04:43:32.00007

我通过API从外部系统(Salesforce Marketing Cloud)获取一些数据,我将以下面的格式获取数据:

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"
 }]

它非常接近JSON,我想将其格式化为JSON文件,以便将其导入我们的数据库.有关如何做到这一点的任何想法?

谢谢

最佳答案
它看起来像一个名为suds的对象,已经在Python中. Fuel-SDK使用它.

suds对象已经为你做了.只需调用您要查找的属性即可.

但是,如果你想要它作为一个dict,附加是它的常用功能:

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))

第一个将它转换为dict,第二个转换为正确的json.

一些有用的链接:
https://fedorahosted.org/suds/wiki/Documentation

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读