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

random832 at random832 at
Fri Aug 28 07:54:32 CEST 2015

On Fri, Aug 28, 2015, at 00:57, 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.

> Is there a way to re-write strip_floatApprox_wrapping to handle both
> ints/floats, and preserve the original format?

You could do simply isinstance(field, (int, float)).

> Or is there a more elegant way to deal with the arbitrary nesting with
> floatApprox?

I'd probably just recursively walk through the dictionary finding these
and removing them.

def clean_floatapprox(obj):
  if type(obj) is dict:
    for key, value in obj.items():
      if type(value) is dict:
        if len(value) == 1 and 'floatApprox' in value:
          obj[key] = value['floatApprox']

Since it's a JSON result I didn't bother with making a copy or dealing
with the possibility of circular references for this example function,
so you'll need to add to this if you have to deal with those things.

Incidentally, do you ever get one that represents a very large value and
has more fields than just floatApprox? I googled this and it looks like
it's a MongoDB thing.

The example given is {"floatApprox" : 9223372036854776000,
    "top" : 2147483647,  "bottom" : 4294967295}

Actually representing the value 9223372036854775807. If top and bottom
are found the result should be top << 32 | bottom. I don't know how
large negative numbers are represented.

More information about the Python-list mailing list