Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Flask : How to convert a dictionary object to json? [duplicate]

Tags:

python

json

flask

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.

like image 438
Paras Avatar asked Oct 25 '25 05:10

Paras


1 Answers

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
}
like image 70
Pankaj Singhal Avatar answered Oct 26 '25 20:10

Pankaj Singhal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!