def swap_inf_nan(val):
 if isinstance(val, string_types):
  return val
 elif isinstance(val, collections.Sequence):
  return [swap_inf_nan(v) for v in val]
 elif isinstance(val, collections.Mapping):
  return dict([(swap_inf_nan(k), swap_inf_nan(v)) for (k, v) in iteritems(val)])
 elif isinstance(val, float):
  if math.isnan(val):
   return '__NaN__'
  elif (val == float('inf')):
   return '__Infinity__'
  elif (val == float('-inf')):
   return '__-Infinity__'
  else:
   return val
 else:
  return val

def swap_inf_nan ( val ) : if isinstance ( val , string_types ) : return val elif isinstance ( val , collections . Sequence ) : return [ swap_inf_nan ( v ) for v in val ] elif isinstance ( val , collections . Mapping ) : return dict ( [ ( swap_inf_nan ( k ) , swap_inf_nan ( v ) ) for ( k , v ) in iteritems ( val ) ] ) elif isinstance ( val , float ) : if math . isnan ( val ) : return '__NaN__' elif ( val == float ( 'inf' ) ) : return '__Infinity__' elif ( val == float ( '-inf' ) ) : return '__-Infinity__' else : return val else : return val
this takes an arbitrary object and preps it for jsonifying safely .