簡體   English   中英

將從JSON獲得的Python字典寫入文件

[英]Write Python dictionary obtained from JSON in a file

我有這個腳本,可以從網頁中提取json對象。 json對象將轉換為字典。 現在,我需要將這些字典寫入文件中。 這是我的代碼:

#!/usr/bin/python

import requests

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

一個文件中有十行。 我需要在該文件中寫字典,該字典由十行組成。我該怎么做? 謝謝。

要解決原始問題,例如:

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())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM