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

Viewed 66

I would like to read a request, sent via curl, as given below:

curl -X POST http://127.0.0.1:8080/eval/res -v path/request.json. With the json having the following format:

{
    "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"
    }]
}

After service initialization, my code is:

 def preprocess(self, data):
    _json = {}
    for row in data:
        json_obj = row.get("data") or row.get("body")
        self.parameter_dict = dict(json_obj)
    image_url = ""
    json_obj = dict(json_obj)
    for img_inputs, msk_inputs in zip(json_obj['imgX'], json_obj['imgY']):
        key = img_inputs['key']

However, that gives:

KeyError: 'img'

I debug and find that when reading json file, each row is a bytearray:

{'body': bytearray(b'')}.

How can I decode to get the .json format back?

1 Answers

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 json

with 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.

Related