4

I'm fairly new to Python. So I have a REST API based on Flask.So I have a dictionary as listed below :

dict = {'left': 0.17037454, 'right': 0.82339555, '_unknown_': 0.0059609693}

I need to add this to my json response object which is like this :

message = {
                            'status': 200,
                            'message': 'OK',
                            'scores': dict 
                        }
                resp = jsonify(message)
                resp.status_code = 200
                print(resp)
                return resp

I'm getting the following error :

....\x.py", line 179, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: 0.027647732 is not JSON serializable

Can some one help me with this? Thanks.

Paras
  • 3,191
  • 6
  • 41
  • 77

2 Answers2

6

The code runs fine for me. Look at the following example server code:

from flask import Flask
from flask import jsonify

app = Flask(__name__)


@app.route('/')
def hello():
    d = {'left': 0.17037454, 'right': 0.82339555, '_unknown_': 0.0059609693}
    message = {
        'status': 200,
        'message': 'OK',
        'scores': d
    }
    resp = jsonify(message)
    resp.status_code = 200
    print(resp)
    return resp

if __name__ == '__main__':
    app.run()

And the following curl returns fine:

$ curl http://localhost:5000/
{
  "message": "OK", 
  "scores": {
    "_unknown_": 0.0059609693, 
    "left": 0.17037454, 
    "right": 0.82339555
  }, 
  "status": 200
}
Pankaj Singhal
  • 15,283
  • 9
  • 47
  • 86
0

This error is seen when you try to jsonify something which is not a pure python dictionary. So simply use pure python objects, which are easily translated to JSON.

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/')
def index():
    dict_obj = {
        'left': 0.17037454, 
        'right': 0.82339555, 
        '_unknown_': 0.0059609693
    }
    message = {
        'status': 200,
        'message': 'OK',
        'scores': dict_obj
    }
    resp = jsonify(message)
    resp.status_code = 200
    print(resp)
    return resp

if __name__ == '__main__':
    app.run(debug=True)

Its a pretty simple code.

When you hit localhost:5000 in your browser after running this code, you see this output

{
  "message": "OK", 
  "scores": {
    "_unknown_": 0.0059609693, 
    "left": 0.17037454, 
    "right": 0.82339555
  }, 
  "status": 200
}

I have used Flask==1.0.2 here.

Few observations:

  1. Don't use dict as a variable name. Its a python keyword.

  2. Follow PEP8 standards while writing the code.

  3. Don't keep trailing whitespaces in the code.

Vishvajit Pathak
  • 3,351
  • 1
  • 21
  • 16
  • It isn't working if my dictionary object is created dynamically. # Sort to show labels in order of confidence top_k = predictions.argsort()[-num_top_predictions:][::-1] result = {} for node_id in top_k: human_string = labels[node_id] score = predictions[node_id] result[human_string] = score print(type(result)) It prints – Paras Aug 27 '18 at 07:59