0

I'm writing som simple request and just can't understant what's wrong

data1 = df.loc[N, 'online_raw_json']
print(type(data1))
print(data1)
data1 = json.dumps(data1)
print(type(data1))
print(data1)

response = requests.post("http://127.0.0.1:5000/predict", json=data1)
print(response.text)

OUTPUT:

<class 'str'>
{"batch_id": 230866, "heat_no": "2019333", "tasks":7, "oxy": 41.6, ... "data": []}]}
<class 'str'>
"{\"batch_id\": 230866, \"heat_no\": \"2019333\", \"tasks\": 7, ... \"data\": []}]}"

So I get error Exception happened in API function: the JSON object must be str, bytes or bytearray, not list

json.dumps must provide "proper" json, but still it is treated like a string.

DDR
  • 459
  • 5
  • 15
  • 2
    Show the full stacktrace – OneCricketeer Apr 06 '21 at 14:07
  • You already have a string, so `json.dumps(data1)` is double-stringing your data – OneCricketeer Apr 06 '21 at 14:08
  • What is full stacktace? – DDR Apr 06 '21 at 14:09
  • 1
    Besides that, requests can accept a dictionary for the `json` parameter https://stackoverflow.com/a/26344315/2308683 – OneCricketeer Apr 06 '21 at 14:09
  • Don't copy the only error message. Copy the full output, that shows exactly what module and code line throws the exception – OneCricketeer Apr 06 '21 at 14:10
  • That's all I got in pycharm. If I print(response), I get . This is a request to a bentoml service (bentoml serve /path/) – DDR Apr 06 '21 at 14:12
  • I don't know what bentoml is. You seem to be calling some localhost server endpoint, which you'd have full logs for. In other words, what is returning the text "the JSON object must be str, bytes or bytearray, not list"? And that appears to be a Python exception message, so you're getting a traceback that shows exactly where the issue is... In particular, focus on why it thinks your JSON is actually a list type – OneCricketeer Apr 06 '21 at 14:15
  • It's best to pass a normal Python object as the json argument, because that way requests will not only handle serialisation, it will also set the correct Content-Type header. – snakecharmerb Apr 06 '21 at 14:25
  • OneCricketeer, you were right. I found the error. It's working now with just a dict, instead of a json-string-construction. – DDR Apr 06 '21 at 14:36

1 Answers1

1

json.dumps is meant to 'dump' a python Dict as a str. So it's working as intended.

In your case you should parse the string to a dict, with json.loads(data1) for example.

data1 = df.loc[N, 'online_raw_json']
data1 = json.loads(data1)

response = requests.post("http://127.0.0.1:5000/predict", json=data1)
print(response.text)