Skip to content
Advertisement

Format floats with standard json module

I am using the standard json module in python 2.6 to serialize a list of floats. However, I’m getting results like this:

JavaScript

I want the floats to be formated with only two decimal digits. The output should look like this:

JavaScript

I have tried defining my own JSON Encoder class:

JavaScript

This works for a sole float object:

JavaScript

But fails for nested objects:

JavaScript

I don’t want to have external dependencies, so I prefer to stick with the standard json module.

How can I achieve this?

Advertisement

Answer

Note: This does not work in any recent version of Python.

Unfortunately, I believe you have to do this by monkey-patching (which, to my opinion, indicates a design defect in the standard library json package). E.g., this code:

JavaScript

emits:

JavaScript

as you desire. Obviously, there should be an architected way to override FLOAT_REPR so that EVERY representation of a float is under your control if you wish it to be; but unfortunately that’s not how the json package was designed.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement