Skip to content

Instantly share code, notes, and snippets.

@ethaizone
Last active October 21, 2024 10:05
Show Gist options
  • Save ethaizone/833903eaf69c3b66c4834e261ba750e2 to your computer and use it in GitHub Desktop.
Save ethaizone/833903eaf69c3b66c4834e261ba750e2 to your computer and use it in GitHub Desktop.
Junior in team asked me if they don't want to see exponential notation in json, how to do in python?
import json
import re
class CustomJSONEncoder(json.JSONEncoder):
def encode_float(self, obj):
if isinstance(obj, float):
return format(obj, "f").rstrip('0').rstrip('.')
return super().encode(obj)
def encodeObj(self, obj):
if isinstance(obj, float):
return self.encode_float(obj)
if isinstance(obj, dict):
return {k: self.encodeObj(v) for k, v in obj.items()}
if isinstance(obj, list):
return [self.encodeObj(v) for v in obj]
return obj
def encode(self, o):
return super().encode(self.encodeObj(o))
def decode_float(obj):
if isinstance(obj, dict):
return {k: decode_float(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [decode_float(i) for i in obj]
elif isinstance(obj, str):
try:
# Regular expression to check if the string contains only digits and at most one full stop
if re.fullmatch(r'[-]?\d*\.?\d+', obj):
return float(obj)
except ValueError:
pass
return obj
data = {
"name": "Sample",
"value": 0.000064,
"meta": {
"details": [1.23, 0.000064, 7.89]
}
}
# Encoding
json_str = json.dumps(data, cls=CustomJSONEncoder)
print(json_str)
# Decoding
decoded_data = json.loads(json_str, object_hook=decode_float)
print(decoded_data)
# ❯ python3 test.py
# {"name": "Sample", "value": "0.000064", "meta": {"details": ["1.23", "0.000064", "7.89"]}}
# {'name': 'Sample', 'value': 6.4e-05, 'meta': {'details': [1.23, 6.4e-05, 7.89]}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment