23

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?

phoenix
  • 7,988
  • 6
  • 39
  • 45
ark
  • 749
  • 3
  • 8
  • 29

3 Answers3

50

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)
phoenix
  • 7,988
  • 6
  • 39
  • 45
Jared
  • 25,627
  • 7
  • 56
  • 61
  • 12
    There's no good reason to deserialize and then re-serialize the JSON. Just write `solditems.content` straight out to file. – Lukasa Jul 08 '13 at 08:53
  • 5
    I was under the impression OP was going to be adjusting it before writing to file. "access and modify,tweak,etc". This is just meant as an example :) – Jared Jul 08 '13 at 09:06
  • just adding info : we don't need to create data.json first, because this answer will generate data.json automatically. – rizkidzulkarnain Oct 02 '21 at 17:17
6

Based on @Lukasa's comment, this accelerates @Jared's solution :

import requests

solditems = requests.get('https://github.com/timeline.json') # (your url)
data = solditems.content
with open('data.json', 'wb') as f:
    f.write(data)
hzitoun
  • 5,492
  • 1
  • 36
  • 43
5

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)
Ben
  • 5,952
  • 4
  • 33
  • 44