labjunky
labjunky

Reputation: 831

Convert a string into dictionary

I have a .js file with the following content:

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

Which I would like to convert it into a python dictionary that I can access as follows

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

What is the best way to achieve this?

Upvotes: 2

Views: 100

Answers (1)

Van Peer
Van Peer

Reputation: 2167

Code

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

Sample output

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

Upvotes: 2

Related Questions