Reputation:
import base64
import requests
USERNAME, PASSWORD = 'notworking', 'notworking'
def send_request():
# Request
try:
response = requests.get(
url="https://api.mysportsfeeds.com/v1.1/pull/nhl/2017-2018-regular/cumulative_player_stats.json",
params={
"fordate": "20171009"
},
headers={
"Authorization": "Basic " +
base64.b64encode('{}:{}'.format(USERNAME,PASSWORD)\
.encode('utf-8')).decode('ascii')
}
)
print('Response HTTP Status Code: {status_code}'.format(
status_code=response.status_code))
print('Response HTTP Response Body: {content}'.format(
content=response.content))
except requests.exceptions.RequestException:
print('HTTP Request failed')
That function gave me a json output. I would like to create a file in which the json output will be formatted so that I could analyse the data. A bit like what we could do with https://jsonformatter.curiousconcept.com/.
How could I do such thing? I have seen that question How to prettyprint a JSON file?, but I am not able to adapt the response to what I want to do.
Upvotes: 0
Views: 771
Reputation: 6160
You're in luck, as this is a very common thing to do in python.
import json
... # Existing code
data = response.json() # Requests has a built in json response parser
with open("my_stylish_file.json", "w") as f:
json.dump(data, f, indent=4)
# The 'indent' is what makes it multiline and automatically indented
Upvotes: 2