Decode a json file properly, when get it as an input via message request Decode a json file properly, when get it as an input via message request json json

Decode a json file properly, when get it as an input via message request


To avoid problems with json responses from APIs, you can use the json lib. In particular json.loads() returns a dictionary so you don't have to convert things manually.

For example:

import jsonwith open('<path_to_file>/request.json','r') as f:    data = f.read()    _json = json.loads(data)    print(_json)

Would output:

{'imgX': [{'key': 'x', 'url': 'http://127.0.0.1:8080/imgs/x.png'}], 'imgY': [{'key': 'y', 'url': 'http://127.0.0.1:8080/imgs/y.png'}]}

On the other hand, when using zip() if you are getting two lists img_inputs and msk_inputs, each with more than one json object/dictionary inside, in order to make img_inputs['key'] work, you would need to loop over the values of those lists to get to the keys.

    #...       for img_inputs, msk_inputs in zip(json_obj['imgX'], json_obj['imgY']):        key = img_inputs[0]['key']    #...

In this case (I revised my code), zip() will return the first element in the list for img_inputs and msk_inputs so that step is not necessary and your for loop is fine.

Make sure you are getting a valid json response from the API.