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?
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.
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.
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.
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.
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With