Thursday 28 July 2016

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('https://api.companieshouse.gov.uk/company/**COMPANY NUMBER**/filing-history', auth=('**AUTH CODE**', ''))


r.json()


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!



Thanks!!


Answer



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:
f.write(json_str)



EDIT: as pointed out in comments by @Tomalak, this code does double conversion, which is clearly not needed here. So you can just



with open(filename, 'w') as f:
f.write(r.text)

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...