MachineLearningNotebooks icon indicating copy to clipboard operation
MachineLearningNotebooks copied to clipboard

Possible double serialization on results returned from web service

Open screamyao opened this issue 8 years ago • 6 comments

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.

screamyao avatar Oct 12 '18 20:10 screamyao

I had the same issue and had to remove the json.dumps in the return from my run().

prasanthpul avatar Oct 12 '18 21:10 prasanthpul

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 avatar Oct 15 '18 16:10 rastala

@rastala is this documented somewhere? consider also updating the notebooks which show always using json.dumps, even on data that wouldn't need it.

prasanthpul avatar Oct 15 '18 16:10 prasanthpul

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

ezwiefel avatar Oct 17 '18 15:10 ezwiefel

Yeah I will fix this. Thx for spotting it!

hning86 avatar Oct 19 '18 03:10 hning86

this is fixed. i am closing the issue.

hning86 avatar Oct 23 '18 16:10 hning86