Possible double serialization on results returned from web service
Noticed strange behavior on results returned from web service after constructing score.py following the SDK documentation. See the below comparison.
Attempt 1. run() function using json.dumps on return:
def run(input_json):
'''
Input: JSON "{\"skill\": \"legal\"}"
'''
try:
input_df = json.loads(input_json)["skill"].lower()
assert len(input_df)>0
except:
print("Input data is not in JSON format")
res = predict(input_df)
res_dict = {"skills" : res}
return json.dumps(res_dict)
Output (notice the excessive backslashes):
"{\"skills\": [\"finance\", \"corporate_finance\"]}"
Attempt 2. run() function simply returning Python dictionary:
def run(input_json):
'''
SAME CODE
'''
return res_dict
Output:
{"skills": ["finance", "corporate_finance"]}
The first output is consistent with applying json.dumps twice.
print(json.dumps(json.dumps({"skills":["finance","corporate_finance"]})))
Result:
"{\"skills\": [\"finance\", \"corporate_finance\"]}"
Makes me wonder if the API service is doing its own json.dumps on returned object already? Hence there should be no need of adding json.dumps in the run() function.
I had the same issue and had to remove the json.dumps in the return from my run().
The service calls Request library's Response.json() method on the return value. So if the return value can be handled by this method already, then json.dumps() wouldn't be necessary.
@rastala is this documented somewhere? consider also updating the notebooks which show always using json.dumps, even on data that wouldn't need it.
I agree with with @prasanthpul - this should be documented somewhere and the notebooks should be updated...
@hning86 - Could we update these notebooks to take out json.dumps() from the score.py examples. This causes malformed JSON to be returned from the webservice.
Additionally, we should have documentation that the return value from the run method in scoring scripts should be a JSON serializable object and not a JSON string
Yeah I will fix this. Thx for spotting it!
this is fixed. i am closing the issue.