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.

1
  • This comment comes rather late but I would assume, using dict as a variable name is a bad idea and could potentially be understood by python as the type name, not as the dictionary and it probably cannot serialize native types to json. Just saying, because no one of the other answers explicitly said it. Commented Sep 12, 2023 at 12:58

2 Answers 2

7

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 } 
Sign up to request clarification or add additional context in comments.

3 Comments

Doing json.dumps on dict and then jsonify(message) will jsonify the dict twice, are you sure that's the right way to do things?
@ThatBird updated
It's likely that your updated example will not work without json.dumps
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.

1 Comment

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 <class 'dict'>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.