I am trying to parse data from an api with python and requests.
SO Reference Python codecs and utf-8 bom error
Listed multiple references above as I have updated script with each error received.
import requests
import codecs
import json
r = requests.get(
"https://api.tatts.com/sales/vmax/web/data/racing/2017/4/05/mr/")
data = json.load(codecs.open(r.json(), 'utf-8-sig'))
# reads = r.json()
# data = reads.decode('utf-8-sig')
with open('data.json', 'w') as f:
json.dump(data, f)
I want to save the response from the api https://api.tatts.com/sales/vmax/web/data/racing/2017/4/05/mr/ to a file.json
Initially I received the below so applied codecs resolution from SO reference answer.
json.decoder.JSONDecodeError: Unexpected UTF-8 BOM (decode using utf-8-sig): line 1 column 1 (char 0)
this resolution from SO answer.
data = json.load(codecs.open(r.json(), 'utf-8-sig'))
Now I receive error that
TypeError: expected str, bytes or os.PathLike object, not dict
However I cannot resolve the typerror because I need to load using codecs to stop the ut8-sig error.
How can I parse and write from requests and avoid both errors?
EDIT
Updated using below answer, however fails to write the file to disk.
import requests
import codecs
import json
r = requests.get(
"https://api.tatts.com/sales/vmax/web/data/racing/2017/4/05/mr/")
data = json.load(codecs.open(r.text, 'r', 'utf-8-sig'))
with open('data.json', 'w') as f:
f.write(data)
Answer
import requests
import json
r = requests.get(
"https://api.tatts.com/sales/vmax/web/data/racing/2017/4/05/mr/")
output = open('data.json', 'w')
output.write(r.text)