Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving a json file to computer python

Using requests in Python I am performing a GET, requesting a JSON file which I can later access and modify, tweak, etc. with the command solditems.json(). However I would like to save this JSON file to my computer. Looking through the requests docs I found nothing, does anybody have an easy way I can do this?

like image 588
ark Avatar asked Jul 08 '13 03:07

ark


People also ask

How do I save a JSON file in Python?

Saving a JSON File We do need to import the json library and open the file. To actually write the data to the file, we just call the dump() function, giving it our data dictionary and the file object.

How do I save a JSON file to my computer?

In Notepad++ on the Language menu you will find the menu item - 'J' and under this menu item chose the language - JSON. Once you select the JSON language then you won't have to worry about how to save it. When you save it it will by default save it as . JSON file, you have to just select the location of the file.

How do you create a JSON file and save it in Python?

To create a json file in Python, use with open() function. The open() function takes the file name and mode as an argument. If the file is not there, then it will be created.

How does Python store JSON data?

We use the json. loads() method to parse a JSON string and return a Python object such as a dictionary. The json. loads() method takes the file contents as a string.


2 Answers

You can do it just as you would without requests. Your code might look something like,

import json
import requests

solditems = requests.get('https://github.com/timeline.json') # (your url)
data = solditems.json()
with open('data.json', 'w') as f:
    json.dump(data, f)
like image 91
Jared Avatar answered Sep 30 '22 14:09

Jared


This is also very easy with the standard library's new pathlib library. Do note that this code is purely "writing the bytes of an HTTP response to a file". It's fast, but it does no validation that the bytes you're writing are valid JSON.

import requests
import pathlib

solditems = requests.get('https://github.com/timeline.json') # (your url)
pathlib.Path('data.json').write_bytes(solditems.content)
like image 20
Ben Avatar answered Sep 30 '22 14:09

Ben