如何将字符串转换为字典

时间:2017-10-20 20:03:53

标签: python string dictionary

我有一个几乎看起来像字典的长字符串。我想将其转换为适当的Python字典。字符串的示例如下:

'{"autorunResult":"0","batteryInfo":"No system battery","cpuBrand":"Intel(R) Xeon(R) CPU E5-1650 v3 @ 3.50GHz","id":"bMlXyTrjXOOo","localeId":"1033","numCores":"1","payloadResult":"0","processorArchitecture":"x64 (AMD or Intel)","systemMemory":"0.2 GB","v":"5","windowsVersion":"Windows 7 Service Pack 1","payloadSaved":true,"autorunSaved":true,"installedApps":["AddressBook","Adobe AIR","com.adobe.mauby.4875E02D9FB21EE389F73B8D1702B320485DF8CE.1","Connection Manager","DirectDrawEx","Fontcore","IE40","IE4Data","IE5BAKEX","IEData","MobileOptionPack","Pillow-py2.7","SchedulingAgent","WIC","{00203668-8170-44A0-BE44-B632FA4D780F}","{26A24AE4-039D-4CA4-87B4-2F83217000FF}","{32A3A4F4-B792-11D6-A78A-00B0D0170000}","{4A03706F-666A-4037-7777-5F2748764D10}","{77DCDCE3-2DED-62F3-8154-05E745472D07}","{AC76BA86-7AD7-1033-7B44-A90000000001}","{BB8B979E-E336-47E7-96BC-1031C1B94561}","{C3CC4DF5-39A5-4027-B136-2B3E1F5AB6E2}"],"autoRunApps":["OptionalComponents","Adobe Reader Speed Launcher","SunJavaUpdateSched","MFDS"]}'

请注意,这看起来像字典的字符串表示。事实上,事实并非如此。这两个k,v对杀了它:"payloadSaved":true,"autorunSaved":true。 (值周围没有双引号)。

基本上,我需要获取长输入字符串并将其转换为字典。任何技巧?

我试过了:

  1. 使用ast.literal_eval。它爆炸......因为上述问题。需要以某种方式清理输入字符串以使其工作。
  2. 取出括号,用逗号标记长字符串,但同样,它会炸弹......(列表值有逗号......)。
  3. 不确定如何继续。

1 个答案:

答案 0 :(得分:-1)

如果那是JSON,那么:

import json
d = json.loads(s)

如果是Python文件:

d = eval(s)

对于字符串键和&价值你会发现没有多大区别。出现true/Truefalse/Falsenull/None值时可能会出现差异,或者在某些情况下可能会显示序列/序列的序列化方式。