Casting to a "number" (both int and float)?

Victor Hooi victorhooi at gmail.com
Fri Aug 28 01:04:51 EDT 2015


Actually, I've just realised, if I just test for numeric or try to cast to ints, this will break for string fields.

As in, the intention is to call strip_floatAprox_wrapping on all the fields I'm parsing, and have it deal with the floatApprox dict wrapping, whether the contents are numbers or strings (although strings would not be wrapped in floatApprox).

On Friday, 28 August 2015 14:58:01 UTC+10, Victor Hooi  wrote:
> I'm reading JSON output from an input file, and extracting values.
> 
> Many of the fields are meant to be numerical, however, some fields are wrapped in a "floatApprox" dict, which messed with my parsing.
> 
> For example:
> 
> {
>     "hostname": "example.com",
>     "version": "3.0.5",
>     "pid": {
>         "floatApprox": 18403
>     }
>     "network": {
>         "bytesIn": 123123,
>         "bytesOut": {
>             "floatApprox": 213123123
>         }
> }
> 
> The floatApprox wrapping appears to happen sporadically in the input.
> 
> I'd like to find a way to deal with this robustly.
> 
> For example, I have the following function:
> 
> def strip_floatApprox_wrapping(field):
>     # Extracts a integer value from a field. Workaround for the float_approx wrapping.
>     try:
>         return int(field)
>     except TypeError:
>         return int(field['floatApprox'])
> 
> which I can then call on each field I want to extract.
> 
> However, this relies on casting to int, which will only work for ints - for some fields, they may actually be floats, and I'd like to preserve that if possible.
> 
> (I know there's a isnumber() field - but you can only call that on a string - so if I do hit a floatApprox field, it will trigger a AttributeError exception, which seems a bit clunky to handle).
> 
> def strip_floatApprox_wrapping(field):
>     # Extracts a integer value from a field. Workaround for the float_approx wrapping.
>     try:
>         if field.isnumeric():
>             return field
>     except AttributeError:
>         return field['floatApprox']
> 
> Is there a way to re-write strip_floatApprox_wrapping to handle both ints/floats, and preserve the original format?
> 
> Or is there a more elegant way to deal with the arbitrary nesting with floatApprox?




More information about the Python-list mailing list