12

I am trying to set the python json library up in order to save to file a dictionary having as elements other dictionaries. There are many float numbers and I would like to limit the number of digits to, for example, 7.

According to other posts on SO encoder.FLOAT_REPR shall be used. However it is not working.

For example the code below, run in Python3.7.1, prints all the digits:

import json
json.encoder.FLOAT_REPR = lambda o: format(o, '.7f' )
d = dict()
d['val'] = 5.78686876876089075543
d['name'] = 'kjbkjbkj'
f = open('test.json', 'w')
json.dump(d, f, indent=4)
f.close()

How can I solve that?

It might be irrelevant but I am on macOS.

EDIT

This question was marked as duplicated. However in the accepted answer (and until now the only one) to the original post it is clearly stated:

Note: This solution doesn't work on python 3.6+

So that solution is not the proper one. Plus it is using the library simplejson not the library json.

roschach
  • 8,390
  • 14
  • 74
  • 124
  • @Tomas Farias In the answer of the question you posted it is clearly stated: `Note: This solution doesn't work on python 3.6+` so I don't think it is a duplicate, unless of course you are sure it works: if so please tell me how. – roschach Jan 25 '19 at 18:00
  • I agree it wasn't a duplicate of that other question. FWIW, I've spent a fair amount of time looking into doing similar things with the `json.JSONEncoder` class in the past, and my conclusion from looking at its source code is that doing this kind of thing is not really feasible without changing the data-structure before passed it in. That said, since the source code is available, so you could create a custom version of the library. Also not that `simplejson` is _very_ similar to Python's own `json` module—to the point that you can almost use them interchangeably. – martineau Jan 26 '19 at 00:49
  • Would you take a look at my solution? If I understand the question correctly, I believe what I posted is the simplest and best. – SwimBikeRun Feb 21 '19 at 03:29
  • @SwimBikeRun the simplest might be but you should never say your answer is the best: it's kind of arrogant and here there are people who might have more experience than you. – roschach Feb 23 '19 at 13:52
  • @FrancescoBoi Yep I looked like a fool on this one :D. I was nearly sure Decode had all the bells and whistles as Encode, as I just did this exact thing but in the other direction. That's what I get for pasting untested code. Oops! – SwimBikeRun Feb 23 '19 at 15:59

7 Answers7

9

It is still possible to monkey-patch json in Python 3, but instead of FLOAT_REPR, you need to modify float. Make sure to disable c_make_encoder just like in Python 2.

import json

class RoundingFloat(float):
    __repr__ = staticmethod(lambda x: format(x, '.2f'))

json.encoder.c_make_encoder = None
if hasattr(json.encoder, 'FLOAT_REPR'):
    # Python 2
    json.encoder.FLOAT_REPR = RoundingFloat.__repr__
else:
    # Python 3
    json.encoder.float = RoundingFloat

print(json.dumps({'number': 1.0 / 81}))

Upsides: simplicity, can do other formatting (e.g. scientific notation, strip trailing zeroes etc). Downside: it looks more dangerous than it is.

proski
  • 3,603
  • 27
  • 27
6

Option 1: Use regular expression matching to round.

You can dump your object to a string using json.dumps and then use the technique shown on this post to find and round your floating point numbers.

To test it out, I added some more complicated nested structures on top of the example you provided::

d = dict()
d['val'] = 5.78686876876089075543
d['name'] = 'kjbkjbkj'
d["mylist"] = [1.23456789, 12, 1.23, {"foo": "a", "bar": 9.87654321}]
d["mydict"] = {"bar": "b", "foo": 1.92837465}

# dump the object to a string
d_string = json.dumps(d, indent=4)

# find numbers with 8 or more digits after the decimal point
pat = re.compile(r"\d+\.\d{8,}")
def mround(match):
    return "{:.7f}".format(float(match.group()))

# write the modified string to a file
with open('test.json', 'w') as f:
    f.write(re.sub(pat, mround, d_string))

The output test.json looks like:

{
    "val": 5.7868688,
    "name": "kjbkjbkj",
    "mylist": [
        1.2345679,
        12,
        1.23,
        {
            "foo": "a",
            "bar": 9.8765432
        }
    ],
    "mydict": {
        "bar": "b",
        "foo": 1.9283747
    }
}

One limitation of this method is that it will also match numbers that are within double quotes (floats represented as strings). You could come up with a more restrictive regex to handle this, depending on your needs.

Option 2: subclass json.JSONEncoder

Here is something that will work on your example and handle most of the edge cases you will encounter:

import json

class MyCustomEncoder(json.JSONEncoder):
    def iterencode(self, obj):
        if isinstance(obj, float):
            yield format(obj, '.7f')
        elif isinstance(obj, dict):
            last_index = len(obj) - 1
            yield '{'
            i = 0
            for key, value in obj.items():
                yield '"' + key + '": '
                for chunk in MyCustomEncoder.iterencode(self, value):
                    yield chunk
                if i != last_index:
                    yield ", "
                i+=1
            yield '}'
        elif isinstance(obj, list):
            last_index = len(obj) - 1
            yield "["
            for i, o in enumerate(obj):
                for chunk in MyCustomEncoder.iterencode(self, o):
                    yield chunk
                if i != last_index: 
                    yield ", "
            yield "]"
        else:
            for chunk in json.JSONEncoder.iterencode(self, obj):
                yield chunk

Now write the file using the custom encoder.

with open('test.json', 'w') as f:
    json.dump(d, f, cls = MyCustomEncoder)

The output file test.json:

{"val": 5.7868688, "name": "kjbkjbkj", "mylist": [1.2345679, 12, 1.2300000, {"foo": "a", "bar": 9.8765432}], "mydict": {"bar": "b", "foo": 1.9283747}}

In order to get other keyword arguments like indent to work, the easiest way would be to read in the file that was just written and write it back out using the default encoder:

# write d using custom encoder
with open('test.json', 'w') as f:
    json.dump(d, f, cls = MyCustomEncoder)

# load output into new_d
with open('test.json', 'r') as f:
    new_d = json.load(f)

# write new_d out using default encoder
with open('test.json', 'w') as f:
    json.dump(new_d, f, indent=4)

Now the output file is the same as shown in option 1.

pault
  • 41,343
  • 15
  • 107
  • 149
  • First of all thanks and sorry for being late in replying. Seems good but now `indent=4` has no effect. – roschach Jan 28 '19 at 09:50
  • @Francesco Not the most elegant solution, but the easiest thing would be to read in the file you wrote and write it back out using the default encoder. The other (more complicated) option would be to update the custom encoder to handle the `kwargs` like `indent`. – pault Jan 28 '19 at 17:15
  • which method(s) should be overloaded for handling `indent`? – roschach Jan 28 '19 at 17:17
  • @FrancescoBoi you could do that inside of `iterencode` similar to how it's done in [`json.JSONEncoder`](https://github.com/python/cpython/blob/master/Lib/json/encoder.py#L259). However, I just had a thought. You could also dump the object to a string and then [use regex to round](https://stackoverflow.com/questions/7584113/rounding-using-regular-expressions) - I'll post an update if I can get that working easily. – pault Jan 28 '19 at 17:21
  • @pault Is there any diference between this complicated answer and simply `class MyCustomEncoder(json.JSONEncoder): def iterencode(self, obj): if isinstance(obj, float): return format(obj, '.7f')` What kind of input are you expecting that's in addition to this? I don't see that in the main question. – SwimBikeRun Feb 21 '19 at 03:20
  • Great answer. Please be aware that if like me you try to write NaN values, format is not enough to convert a float to JSON. You have to take care of some values like, `float('nan') -> NaN`, `float('inf') -> Infinity`, `-float('inf') -> -Infinity` – Hulud Apr 21 '20 at 11:59
  • @SwimBikeRun, your code does not handle nested objects containing floats – xuancong84 Jun 30 '20 at 09:04
1

Here's something that you may be able to use that's based on my answer to the question:

    Write two-dimensional list to JSON file.

I say may because it requires "wrapping" all the float values in the Python dictionary (or list) before JSON encoding it with dump().

(Tested with Python 3.7.2.)

from _ctypes import PyObj_FromPtr
import json
import re


class FloatWrapper(object):
    """ Float value wrapper. """
    def __init__(self, value):
        self.value = value


class MyEncoder(json.JSONEncoder):
    FORMAT_SPEC = '@@{}@@'
    regex = re.compile(FORMAT_SPEC.format(r'(\d+)'))  # regex: r'@@(\d+)@@'

    def default(self, obj):
        return (self.FORMAT_SPEC.format(id(obj)) if isinstance(obj, FloatWrapper)
                else super(MyEncoder, self).default(obj))

    def iterencode(self, obj, **kwargs):
        for encoded in super(MyEncoder, self).iterencode(obj, **kwargs):
            # Check for marked-up float values (FloatWrapper instances).
            match = self.regex.search(encoded)
            if match:  # Get FloatWrapper instance.
                id = int(match.group(1))
                float_wrapper = PyObj_FromPtr(id)
                json_obj_repr = '%.7f' % float_wrapper.value  # Create alt repr.
                encoded = encoded.replace(
                            '"{}"'.format(self.FORMAT_SPEC.format(id)), json_obj_repr)
            yield encoded


d = dict()
d['val'] = FloatWrapper(5.78686876876089075543)  # Must wrap float values.
d['name'] = 'kjbkjbkj'

with open('float_test.json', 'w') as file:
    json.dump(d, file, cls=MyEncoder, indent=4)

Contents of file created:

{
    "val": 5.7868688,
    "name": "kjbkjbkj"
}

Update:

As I mentioned, the above requires all the float values to be wrapped before calling json.dump(). Fortunately doing that could be automated by adding and using the following (minimally tested) utility:

def wrap_type(obj, kind, wrapper):
    """ Recursively wrap instances of type kind in dictionary and list
        objects.
    """
    if isinstance(obj, dict):
        new_dict = {}
        for key, value in obj.items():
            if not isinstance(value, (dict, list)):
                new_dict[key] = wrapper(value) if isinstance(value, kind) else value
            else:
                new_dict[key] = wrap_type(value, kind, wrapper)
        return new_dict

    elif isinstance(obj, list):
        new_list = []
        for value in obj:
            if not isinstance(value, (dict, list)):
                new_list.append(wrapper(value) if isinstance(value, kind) else value)
            else:
                new_list.append(wrap_type(value, kind, wrapper))
        return new_list

    else:
        return obj


d = dict()
d['val'] = 5.78686876876089075543
d['name'] = 'kjbkjbkj'

with open('float_test.json', 'w') as file:
    json.dump(wrap_type(d, float, FloatWrapper), file, cls=MyEncoder, indent=4)
martineau
  • 119,623
  • 25
  • 170
  • 301
1

Here is a python code snippet that shows how to quantize json output to the specified number of digits:

#python example code, error handling not shown

#open files
fin  = open(input_file_name)
fout = open(output_file_name, "w+")

#read file input (note this could be done in one step but breaking it up allows more flexibilty )
indata = fin.read()

# example quantization function
def quant(n):
    return round((float(n) * (10 ** args.prec))) / (
        10 ** args.prec
    )  # could use decimal.quantize

# process the data streams by parsing and using call back to quantize each float as it parsed
outdata = json.dumps(json.loads(indata, parse_float=quant), separators=(",", ":"))

#write output
fout.write(outdata)

The above is what the jsonvice command-line tool uses to quantize the floating-point json numbers to whatever precision is desired to save space.

https://pypi.org/project/jsonvice/

This can be installed with pip or pipx (see docs).

pip3 install jsonvice

Disclaimer: I wrote this when needing to test quantized machine learning model weights.

zkoza
  • 2,644
  • 3
  • 16
  • 24
deftio
  • 51
  • 6
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/30887800) – zkoza Jan 23 '22 at 20:21
  • @zkoza appreciate feedback, included source code and other material – deftio Jan 24 '22 at 04:02
1

I found the above options within the python standard library to be very limiting and cumbersome, so if you're not strictly limited to the python standard lib, pandas has a json module that includes a dumps method which has a double_precision parameter to control the number of digits in a float (default 10):

import json
import pandas.io.json

d = {
  'val': 5.78686876876089075543,
  'name': 'kjbkjbkj',
}

print(json.dumps(d))
print(pandas.io.json.dumps(d))
print(pandas.io.json.dumps(d, double_precision=5))

gives:

{"val": 5.786868768760891, "name": "kjbkjbkj"}
{"val":5.7868687688,"name":"kjbkjbkj"}
{"val":5.78687,"name":"kjbkjbkj"}
Steven D.
  • 493
  • 4
  • 12
0

Doesn't answer this question, but for the decoding side, you could do something like this, or override the hook method.

To solve this problem with this method though would require encoding, decoding, then encoding again, which is overly convoluted and no longer the best choice. I assumed Encode had all the bells and whistles Decode did, my mistake.

# d = dict()
class Round7FloatEncoder(json.JSONEncoder): 
    def iterencode(self, obj): 
        if isinstance(obj, float): 
            yield format(obj, '.7f')


with open('test.json', 'w') as f:
    json.dump(d, f, cls=Round7FloatEncoder)
SwimBikeRun
  • 4,192
  • 11
  • 49
  • 85
  • What version of python are you using? This code throws `TypeError: 'NoneType' object is not iterable` when I try it on 3.6.5. **Edit** Same error on 2.7.14. – pault Feb 21 '19 at 15:08
  • Thanks for your answer thriathlon-athlete :) currently I am unable to test your answer but I will as soon as possible. – roschach Feb 22 '19 at 16:18
  • Ah I see my mistake. To get this to work, would have to encode first, do this method on the decoding, then encode one last time. And that is no less convoluted than the above solutions. I stand corrected – SwimBikeRun Feb 23 '19 at 05:29
0

Inspired by this answer, here is a solution that works for Python >= 3.6 (tested with 3.9) and that allows customization of the format on a case by case basis. It works for both json and simplejson (tested with json=2.0.9 and simplejson=3.17.6).

Note however that this is not thread-safe.

from contextlib import contextmanager


class FormattedFloat(float):
    def __new__(self, value, fmt=None):
        return float.__new__(self, value)

    def __init__(self, value, fmt=None):
        float.__init__(value)
        if fmt:
            self.fmt = fmt
    
    def __repr__(self):
        if hasattr(self, 'fmt'):
            return f'{self:{self.fmt}}'
        return float.__repr__(self)


@contextmanager
def formatted_floats():
    c_make_encoder = json.encoder.c_make_encoder
    json_float = json.encoder.float
    json.encoder.c_make_encoder = None
    json.encoder.float = FormattedFloat
    try:
        yield
    finally:
        json.encoder.c_make_encoder = c_make_encoder
        json.encoder.float = json_float

Example

x = 12345.6789
d = dict(
    a=x,
    b=FormattedFloat(x),
    c=FormattedFloat(x, '.4g'),
    d=FormattedFloat(x, '.08f'),
)

>>> d
{'a': 12345.6789, 'b': 12345.6789, 'c': 1.235e+04, 'd': 12345.67890000}

Now,

with formatted_floats():
    out = json.dumps(d)

>>> out
'{"a": 12345.6789, "b": 12345.6789, "c": 1.235e+04, "d": 12345.67890000}'

>>> json.loads(out)
{'a': 12345.6789, 'b': 12345.6789, 'c': 12350.0, 'd': 12345.6789}

Note that the original json.encoder attributes are restored by the context manager, so:

>>> json.dumps(d)
'{"a": 12345.6789, "b": 12345.6789, "c": 12345.6789, "d": 12345.6789}'
Pierre D
  • 24,012
  • 7
  • 60
  • 96