2

Webページから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']

ファイルには 10 行あります。そのファイルに 10 行からなる辞書を書き込む必要があります..どうすればよいですか? ありがとう。

4

1 に答える 1

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())
于 2012-09-22T06:00:31.293 に答える