【问题标题】:python output string from server into dictionarypython从服务器输出字符串到字典
【发布时间】:2013-04-30 09:44:21
【问题描述】:

如何转换如下字符串

str1='{"data":{"infostore":{"view":"infostore/split"},"mail":>>>{"auto_save_drafts":3,"select_first_message":true,"showname":false,"htmlmessage":true,"signatures":[],"view":"mail/hsplit/unthreaded","autocomplete":true,"formatmessage":"ALTERNATIVE","editor_featureset":2,"fullmailheader":true,"notifyacknoledge":true},"portal":{"externalcontents":[],"internalcontents":[{"module":"mail","visible":true,"external":false,"adj":{"y":0,"x":0},"params":{"limit":5},"header":"E-Mail"},{"module":"calendar","visible":true,"external":false,"adj":{"y":0,"x":1},"params":{"limit":5},"header":"Calendar"},{"module":"contacts","visible":false,"external":false,"adj":{"y":1,"x":2},"params":{"limit":5},"header":"Contacts"},{"module":"infostore","visible":true,"external":false,"adj":{"y":1,"x":0},"params":{"limit":5},"header":"InfoStore"},{"module":"tasks","visible":true,"external":false,"adj":{"y":1,"x":1},"params":{"limit":5},"header":"Tasks"}]},"global":{"minicalendar":{"expanded":false},"confirmpopup":true,"save":1,"autorefresh":10,"landing_page":{"module":"portal"}},"menu":{"menuiteration":2},"wizard":{"firstrun":false,"launchOnStart":false},"categories":{"local":[]},"effects":{"global":false,"hover":{"infostore":true,"mail":false,"speed":3,"portal":true,"tasks":true,"contacts":true,"calendar":true},"fading":false},"tasks":{"interval":30,"gridsort":"asc","view":"tasks/split"},"contacts":{"gridsort":"asc","cardsToViewPerColumn":"auto","view":"contacts/cards"},"calendar":{"workweek":{"countdays":5,"numberofappointments":2,"startday":1},"endtime":18,"autoadd_participant_public":true,"allfolders":true,"starttime":6,"default_reminder":15,"interval":30,"views":{"shared":true,"list":"workweek","team":"workweek","view":"calendar","calendar":"workweek"},"teamview":{"workingTimeOnly":true},"day":{"numberofappointments":4},"view":"calendar/calendar/workweek","custom":{"countdays":3,"numberofappointments":3}}}}'

到字典里?

【问题讨论】:

  • 试试ast.literal_eval(str1)
  • 字符串的格式不适合使用它。 (这是我的第一个想法)。它有一些无效的字符序列。
  • @mata 请提交作为答案!我会支持它;)这绝对是一个错字,所以你的解决方案有效

标签: python python-3.x


【解决方案1】:

您是从 python 解释器会话中复制的,还是 >>>s 真的是字符串的一部分?

如果是这样,那么这看起来像json,那么为什么不使用json.loads()

import json
str1 = ...
obj = json.loads(str1)

【讨论】:

    【解决方案2】:

    您应该删除>>>,然后使用json.loads()

    import json
    str1 = str1.replace('>>>', '')
    dict1 = json.loads(str1)
    

    否则你也使用eval(),但这不是一个好的和安全的解决方案。

    【讨论】:

      猜你喜欢
      • 2015-10-20
      • 1970-01-01
      • 2012-10-11
      • 2019-09-26
      • 2018-11-30
      • 1970-01-01
      • 1970-01-01
      • 2014-09-16
      • 2020-09-25
      相关资源
      最近更新 更多