Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to set encoder format for Python JSON

📅 2017-Jul-12 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ float, json, python ⬩ 📚 Archive

Python's JSON module makes it very easy to dump data into a JSON file. However, I have found that the float values are encoded with a lot of decimal places or in scientific notation. There is no elegant method to set the formatting in the float encoder of the JSON module. The best solution seems to be to monkey patch its formatting option:

# Make json.dump() encode floats with 5 places of precision
import json
json.encoder.FLOAT_REPR = lambda x: format(x, '.5f')

Reference: https://stackoverflow.com/questions/1447287