2

I have this script which abstract the json objects from the webpage. The json objects are converted into dictionary. Now I need to write those dictionaries in a file. Here's my code:

#!/usr/bin/python

import requests

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

There are ten lines in a file. I need to write the dictionary in that file which consist of ten lines..How do I do that? Thanks.

2
  • 1
    Wait a second.... why don't you just save the JSON itself? Commented Sep 22, 2012 at 6:03
  • I need to save objects in the easiest way possible in to a file..It hasn't be the python dictionary. Commented Sep 22, 2012 at 6:31

1 Answer 1

5

To address the original question, something like:

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 ..

note that not every item will be a repository, there are also gist events (etc?).

Better, would be to just save the json to file.

#!/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))

then, you can open it:

with open("yourfilepath.json", "r") as f:
    obj = json.loads(f.read())
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer. How can I just save the json into the file. I want to save the returned objects in the easiest way possible. Can you please edit your answer. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.