2017-10-12 9 views
2

に文字列を変換します私は以下の内容を含む.jsファイル持っている辞書

私は

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

を次のように、私がアクセスできるPythonの辞書に変換したい

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

をこれを達成する最良の方法は何ですか?

+0

https://stackoverflow.com/questions/24027589/how-to-convert-raw-javascript-object-to-python-dictionary – chakri

+0

ここではこれを[parse-json](http://docs.python-guide.org/en/latest/scenarios/json/#parsing-json) – PetarP

+0

@PetarPありがとうの良い例です。しかし、有効なjson文字列ではありません – labjunky

答えて

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' 
+0

URLから「:」を取り除くという問題があります。 – labjunky

+0

を指摘してくれてありがとう.. 'd ['AppSettings'] ['url'] = d ['AppSettings'] ['url'] .replace( 'https //'、 'https://')' –

関連する問題