I have a web service written in Python 3.4 that uses the Falcon framework. One particular method accepts a post of json values. My code:
try:
raw_json = req.stream.read()
except Exception as ex:
raise falcon.HTTPError(falcon.HTTP_400, 'Error', ex.message)
try:
result_json = json.loads(raw_json.decode('utf-8'))
except ValueError:
raise falcon.HTTPError(falcon.HTTP_400,
'Malformed JSON', 'Could not decode the request body. The JSON was incorrect.')
clientIp = result_json['c']
wpIp = result_json['w']
lan = result_json['l']
table = int(result_json['t'])
This code was working fine 9 months ago but currently throws the error: "list indices must be integers or slices, not str." I think it likely broke after a Python or Falcon package update.
The ouput of raw_json.decode('utf-8') looks ok, returning [{"w": "10.191.0.2", "c": "10.191.0.3", "l": "255.255.255.0", "t": "4"}]. I think json.loads() is the root of my problem. len(result_json) is returning 1 where I would expect 4. Is there an additional parameter needed for json.loads() to help it parse correctly? Or am I missing something else entirely?
Thanks, Greg (Python noob)
The returned result [{"w": "10.191.0.2", "c": "10.191.0.3", "l": "255.255.255.0", "t": "4"}]
is a json array, which is parsed into a python list. Therefore
result_json['c']
produces the the mentioned error. Maybe there was a change in the API and it now returns an array where it previously returned a json object.
This should work:
clientIp = result_json[0]['c']
...