Instead of traversing entire structure I hoped to use json.JSONEncoder, but I'm unable to get it to trigger on strings:
#!/usr/bin/env python3
import json
import datetime
class StringShortener(json.JSONEncoder):
def default(self, obj):
strl = 10
if not isinstance(obj, (int,float)) and len(str(obj))>strl:
return str(obj)[:strl] + f"<<cut at {strl}>>"
return obj
mystruct = {
"dummy": "foobar just being more than 10char long",
"dt": datetime.datetime.now()
}
# only shortening the td object
print(json.dumps(mystruct, cls=StringShortener))
Gives:
{"dummy": "foobar just being more than 10char long", "dt": "2022-09-22<<cut at 10>>"}
But key 'dummy's value also match the stringShortener:
>>> obj = "foobar just being more than 10char long"
>>> bool(not isinstance(obj, (int,float)) and len(str(obj))>10)
True
>>> str(obj)[:10] + f"<<cut at 10>>"
'foobar jus<<cut at 10>>'
How can this be fixed so str types also get shortened?