Ruthus99 Ruthus99 - 1 month ago 4
JSON Question

How to download text as a .json file in python using the requests library

I am trying to use an API (notably the companieshouse one) and have managed to get it working to the point where I can use the command line to make a request to the API website and have data returned, I do this using the following code:

r = requests.get('**COMPANY NUMBER**/filing-history', auth=('**AUTH CODE**', ''))


This works insofar as it spits out the relevant information in the command line interface, however what I really want to do is save that data to my computer, preferably in the .json format. Most solutions I have found online deal with using the requests module to download direct images or webpages from the internet but can't help when it comes to turning text into a file then downloading it.

Hopefully someone here can point me in the right direction and help me out, or worse, tell me its not even possible. Let me know if you need any clarification!



You can make a string out of your JSON like this:

import json
json_str = json.dumps(r.json())

And then save it as a regular text file using standard methods.

with open(filename, 'w') as f: