2012-09-22 60 views
2

我有從腳本中抽取json對象的腳本。 json對象被轉換成字典。現在我需要將這些字典寫入一個文件中。這是我的代碼:將從JSON獲取的Python字典寫入文件

#!/usr/bin/python 

import requests 

r = requests.get('https://github.com/timeline.json') 
for item in r.json or []: 
    print item['repository']['name'] 

文件中有十行。我需要在該文件中編寫包含十行代碼的字典......我該怎麼做?謝謝。

+0

你想它作爲JSON? –

+1

等一下....你爲什麼不保存JSON本身? –

+0

我需要以最簡單的方式保存對象到一個文件..它不是Python字典。 –

回答

5

爲了解決原來的問題,是這樣的:

with open("pathtomyfile", "w") as f: 
    for item in r.json or []: 
     try: 
      f.write(item['repository']['name'] + "\n") 
     except KeyError: # you might have to adjust what you are writing accordingly 
      pass # or sth .. 

注意,不是每一個項目將是一個倉庫,也有要點事件(等?)。

更好的辦法是將json保存到文件中。

#!/usr/bin/python 
import json 
import requests 

r = requests.get('https://github.com/timeline.json') 

with open("yourfilepath.json", "w") as f: 
    f.write(json.dumps(r.json)) 

然後,你就可以打開它:

with open("yourfilepath.json", "r") as f: 
    obj = json.loads(f.read()) 
+0

謝謝你的回答。我怎麼才能將json保存到文件中。我想以最簡單的方式保存返回的對象。你可以請編輯你的答案。謝謝。 –