1

I am trying to convert json from an external api to an xls file using requests and tablib. In order to do this, I send a request to the external api, which returns a valid json file. This is my code:

response = req.request("GET", url, params=querystring)
response.json()
data = tb.Dataset()
data.json = response.read()

This is what I get:

Traceback (most recent call last):
  File "...\python\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File ".../python/Scripts/myscript", line 37, in submit
    data.json = response.read()
AttributeError: 'Response' object has no attribute 'read'

If the code is,

 response = req.request("GET", url, params=querystring)
 response.json()
 data = tb.Dataset()
 data.json = response.json()

I get:

Traceback (most recent call last):
  File "...\Bitnami\djangostack-3.0.5-1\python\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "...\Bitnami/djangostack-3.0.5-1/python/Scripts/buzzsumo.py", line 37, in submit
    data.json = response.json()
  File "...\Bitnami\djangostack-3.0.5-1\python\lib\site-packages\tablib\formats\__init__.py", line 66, in __set__
    return self._format.import_set(obj, normalize_input(val))
  File "...\Bitnami\djangostack-3.0.5-1\python\lib\site-packages\tablib\formats\_json.py", line 38, in import_set
    dset.dict = json.load(in_stream)
  File "...\Bitnami\djangostack-3.0.5-1\python\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
AttributeError: 'dict' object has no attribute 'read'

What am I doing wrong?

budgiebeaks
  • 159
  • 9
  • 1
    use `data.json = response.json()` instead of `data.json = response.read()` – Anwarvic May 20 '20 at 20:17
  • 1
    Your first call to `response.json()` doesn't do anything useful; it returns the decoded JSON object, which you then ignore. It doesn't modify the response, so that `response.read()` later returns a decoded object rather than a raw byte stream. – chepner May 20 '20 at 20:30
  • @Anwarvic I actually used exactly that initially, and got a similar error. Please see the updated question. – budgiebeaks May 21 '20 at 11:48
  • @budgiebeaks, try using `import json; json.dumps(response.json())` – Anwarvic May 21 '20 at 14:43

0 Answers0