Code Yarns β€πŸ‘¨β€πŸ’»
Tech Blog ❖ Personal 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


Β© 2022 Ashwin Nanjappa β€’ All writing under CC BY-SA license β€’ 🐘 @codeyarns@hachyderm.io β€’ πŸ“§