将字符串转换为字典

时间:2017-10-12 06:11:31

标签: python

我有一个包含以下内容的.js文件:

AppSettings = {
               projectName:'myproject',
               url: 'https://www.google.com',
               appKey: 'k2y-myproject_124439_18111',
               newsKey: '',
               version: moment().format('YYMMDD_HHmmss'),
               mixpanelToken: '08e97bef3930f330037d9z6t56395060'
              };

我想把它转换成我可以访问的python字典,如下所示

>>> print(data['AppSettings']['url']
>>> 'https://www.google.com'

实现这一目标的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

代码

d = {'AppSettings':{}}
with open('tt.js', 'r') as f:
    next(f)
    for line in f:
        splitLine = line.strip().replace(',','').split(':')
        d['AppSettings'][splitLine[0]] = "".join(splitLine[1:])

d['AppSettings']['url']=d['AppSettings']['url'].replace('htt‌​ps//','https://')
d['AppSettings'].pop("}", None) #remove last item "}" from dict

print(d['AppSettings']['url'])
print(d['AppSettings']['newsKey'])
print(d['AppSettings']['appKey'])
print(d['AppSettings']['version'])
print(d['AppSettings']['mixpanelToken'])

示例输出

'https://www.google.com'
''
'k2y-myproject_124439_18111'
moment().format('YYMMDD_HHmmss')
'08e97bef3930f330037d9z6t56395060'