Would this work for you?

import struct
floatval = 0.6441726684570312
s = struct.pack("d", floatval) # converts floatval into a string (Python 2) or bytes (Python 3), of 8 raw bytes
# then serialise s

To be portable between different platforms, you would also need to store whether the format is little-endian or big-endian (sys.byteorder is 'big' or 'little'; I don't know what it does on bi-endian machines).
Rob Cliffe


On 08/08/2019 20:05:50, Richard Musil wrote:
I am not sure `(str(o),)` is what I want. For a comparison here are three 
examples:
```
json:orig = {"val": 0.6441726684570313}
json:pyth = {'val': 0.6441726684570312}
json:seri = {"val": 0.6441726684570312}

dson:orig = {"val": 0.6441726684570313}
dson:pyth = {'val': Decimal('0.6441726684570313')}
dson:seri = {"val": ["0.6441726684570313"]}

sjson:orig = {"val": 0.6441726684570313}
sjson:pyth = {'val': Decimal('0.6441726684570313')}
sjson:seri = {"val": 0.6441726684570313}
```
Each one has three outputs, `orig` is the input text, `pyth` is its python 
representation in a `dict`, `seri` is the serialized text output of `pyth`.

Now, the prefixes are `json` for standard Python module (which gets the last 
digit different from the output). `dson` is standard Python module using 
`parse_float=decimal.Decimal` on `json.loads` and custom serializer with 
proposed `return (str(o),)`. Finally `sjson` is `simplejson` using 
`use_decimal=True` on `json.loads` and the same (which is default) on its 
`json.dumps`.

When I had `return str(o)` in the custom impl. I ended up with the string in 
the output:
```
dson:orig = {"val": 0.6441726684570313}
dson:pyth = {'val': Decimal('0.6441726684570313')}
dson:seri = {"val": "0.6441726684570313"}
```
and finally, with `return float(o)` I am basically back at the square one:
```
dson:orig = {"val": 0.6441726684570313}
dson:pyth = {'val': Decimal('0.6441726684570313')}
dson:seri = {"val": 0.6441726684570312}
```
The possibility to specify the "raw" textual output, which does not get mangled 
by the JSONEncoder when custom encoder is used seems to be missing.
˙``
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/5JKBNFEH242GCB2JHNDPVA4ACY2TWU23/
Code of Conduct: http://python.org/psf/codeofconduct/


---
This email has been checked for viruses by AVG.
https://www.avg.com
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/H7KGOCOC3WKL7XMWA5PUVEOZ7MC3HX3H/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to