Casting to a "number" (both int and float)?
Victor Hooi
victorhooi at gmail.com
Fri Aug 28 03:56:14 EDT 2015
Hi,
Thanks heaps to everybody for their suggestions/advice =).
Currently I'm using this:
def strip_floatApprox_wrapping(field):
# Extracts a integer value from a field. Workaround for the float_approx wrapping.
if isinstance(field, dict):
return field['floatApprox']
else:
return field
I was a little hesitant to go down that path (using isinstance()) since it seems a bit "un-Pythonic" but it seems to do what I want in a minimal amount of code.
Somebody suggested going through and transforming the whole output from json.loads() in a single pass - I don't actually need *all* the fields, just a fair number of them - is there a particularly strong reason stripping out the floatApprox()'s first is a good approach?
Also, to answer somebody's question - yes, this is MongoDB, specifically the output from db.serverStatus(). The logging and reporting consistency in MongoDB is...quirky, shall we say.
Cheers,
Victor
On Friday, 28 August 2015 16:15:21 UTC+10, Jussi Piitulainen wrote:
> Ben Finney writes:
>
> > Victor Hooi writes:
> [- -]
> >> For example:
> >>
> >> {
> >> "hostname": "example.com",
> >> "version": "3.0.5",
> >> "pid": {
> >> "floatApprox": 18403
> >> }
> >> "network": {
> >> "bytesIn": 123123,
> >> "bytesOut": {
> >> "floatApprox": 213123123
> >> }
> >> }
>
> [- -]
>
> > In JSON there is no distinction at all, the only numeric type is
> > 'float'. What information is there in the input that can be used to
> > know which values should result in an 'int' instance, versus values
> > that should result in a 'float' instance?
>
> I seem to get ints in the example data.
>
> >>> json.load(io.StringIO('{"floatApprox":31213}'))
> {'floatApprox': 31213}
More information about the Python-list
mailing list