Helgi Borg
Helgi Borg

Reputation: 876

How to implement custom json formatter in Python Flask that rounds floats?

Is it possible, in a simple way, to make jsonify format floats to one decimal point?

Here is a simple example. How can I add custom json encoder to this:

from flask import Flask, jsonify
from flask.ext.restful import Api, Resource

app = Flask(__name__)
api = Api(app)

class Test(Resource):
    def get(self):
        return jsonify({'data': [.444, .456]});

api.add_resource(Test, '/')

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

So that the output would be:

{
  "data": [
    0.4, 
    0.5
  ]
}

Upvotes: 3

Views: 3394

Answers (1)

Maarten
Maarten

Reputation: 492

If this is just about rounding floats you can check this answer: how to round off a floating number in python

And for writing custom JSON Encoder this snippet: Custom Flask JSONEncoder

The flask source JSON library here

EDIT: The question here remains what you want to do with what type of data, also when you want to do it. In some cases you might not want to apply any changes to it at all. You have the option to first check the type and then determine what to do with the data before passing it to the encoder or put all that logic into the custom encoder class itself.

Small example:

import json
import math

from flask.json import dumps, JSONEncoder


def round_float(data):
    if type(data) is float:
        rounded = math.ceil(data*100)/100
        return rounded
    else:
        raise TypeError('data must be a float not %s' %type(data))


class CustomJSONEncoder(JSONEncoder):
    def default(self, o):
        #alternatively do the type checking in the default method
        if type(o) is float:
            return round_float(o)
        if type(o) is int:
            return float(o)

encoder = CustomJSONEncoder()

data = dict(floated=encoder.default(2))
data2 = dict(rounded=encoder.default(0.896))

dumps(data)
dumps(data2)

will output:

{"floated": 2.0}
{"rounded": 0.9}

Upvotes: 2

Related Questions