skip to Main Content

I’m trying to call a response from an API. I’m not sure what is wrong, maybe the response isn’t valid JSON but I’m not sure. It doesn’t seem the json module is initialising either. I’ve managed to call the data without json.loads(data) but I need to turn the response in to a dict so I can then use it in a formatted string e.g. print("Here are three suggested FAST terms for the {query}: ", {auth1}, {fast_id1}, {auth2}, {fast_id2}, {auth3}, {fast_id3})

Code:

### assignFAST
# https://www.oclc.org/developer/api/oclc-apis/fast-api/assign-fast.en.html
# http://fast.oclc.org/searchfast/fastsuggest?&query=[query]&queryIndex=[queryIndex]&queryReturn=[queryReturn]&suggest=autosuggest&rows=[numRows]&callback=[callbackFunction]

import json
import requests

### CALLING API
data = requests.get('http://fast.oclc.org/searchfast/fastsuggest?&query=hog&queryIndex=suggestall&queryReturn=suggestall%2Cidroot%2Cauth%2Ctag%2Ctype%2Craw%2Cbreaker%2Cindicator&suggest=autoSubject&rows=3&callback=testcall').text

data_text = json.loads(data)

print(data_text)

Error:

Traceback (most recent call last):
  File "c:Users001255336OneDriveDocumentsCodingassignFASTassignFAST_V1.py", line 10, in <module>
    data_text = json.loads(data)
                ^^^^^^^^^^^^^^^^
  File "C:Users001255336AppDataLocalProgramsPythonPython311Libjson__init__.py", line 346, in loads 
    return _default_decoder.decode(s)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:Users001255336AppDataLocalProgramsPythonPython311Libjsondecoder.py", line 337, in decode 
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:Users001255336AppDataLocalProgramsPythonPython311Libjsondecoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

2

Answers


  1. Because your json is not correct. Your variable data is of type string and therefore can’t be loaded as json

    enter image description here

    Login or Signup to reply.
  2. There is a prefix in the response

    data[:10]
    'testcall({'
    

    If you cut it out it works

    data_text = json.loads(data[9:-1])
    

    However it seems like the site does not work property because it doesn’t deliver correct json

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search