You can do something in this direction:
import json import math target=[1.1,1,2.2,float('inf'),float('nan'),'a string',int(2)] def ffloat(f): if not isinstance(f,float): return f if math.isnan(f): return 'custom NaN' if math.isinf(f): return 'custom inf' return f print 'regular json:',json.dumps(target) print 'customized:',json.dumps(map(ffloat,target))
Print
regular json: [1.1, 1, 2.2, Infinity, NaN, "a string", 2] customized: [1.1, 1, 2.2, "custom inf", "custom NaN", "a string", 2]
If you want to process nested data structures, this is also not so difficult:
import json import math from collections import Mapping, Sequence def nested_json(o): if isinstance(o, float): if math.isnan(o): return 'custom NaN' if math.isinf(o): return 'custom inf' return o elif isinstance(o, basestring): return o elif isinstance(o, Sequence): return [nested_json(item) for item in o] elif isinstance(o, Mapping): return dict((key, nested_json(value)) for key, value in o.iteritems()) else: return o nested_tgt=[1.1,{1.1:float('inf'),3.3:5},(float('inf'),2.2),] print 'regular json:',json.dumps(nested_tgt) print 'nested json',json.dumps(nested_json(nested_tgt))
Print
regular json: [1.1, {"3.3": 5, "1.1": Infinity}, [Infinity, 2.2]] nested json [1.1, {"3.3": 5, "1.1": "custom inf"}, ["custom inf", 2.2]]