Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is json.dumps guaranteed not to lose floating point precision?

Tags:

python

I am talking of a JSON conversion like:

>>> a = {'asas': 1/7.0}
>>> b = json.dumps(a)
>>> c = json.loads(b)
>>> c
{u'asas': 0.14285714285714285}
>>> c['asas'] == 1.0/7
True

Is the JSON encoding guaranteed not to roundoff the number?

In my How to store a floating point number as text without losing precision?, Mark Dickinson says that repr doesnt cause loss of precision. Does json.dumps use the repr?

like image 271
Jesvin Jose Avatar asked Jun 20 '12 10:06

Jesvin Jose


People also ask

What JSON dumps will do?

dumps() json. dumps() function converts a Python object into a json string. skipkeys: If skipkeys is True (default: False), then dict keys that are not of a basic type (str, int, float, bool, None) will be skipped instead of raising a TypeError.

What is the difference between JSON dumps and JSON dump?

json. dump() method used to write Python serialized object as JSON formatted data into a file. json. dumps() method is used to encodes any Python object into JSON formatted String.

Does JSON dumps return a string?

jsonify() returns a Response object with the application/json mimetype set, whereas json. dumps() simply returns a string of JSON data.

What is JSON dump indent?

The indent parameter specifies the spaces that are used at the beginning of a line. We can use the indent parameter of json. dump() to specify the indentation value. By default, when you write JSON data into a file, Python doesn't use indentations and writes all data on a single line, which is not readable.


1 Answers

There is no mention of repr anywhere in the json docs, but it is the current implementation of float-to-string coercion:

FLOAT_REPR = repr

(Lib/json/encoder.py, line 31)

You can build your own JSONEncoder if you want a strict guarantee.

like image 101
Fred Foo Avatar answered Oct 19 '22 23:10

Fred Foo