[ase-users] storing bytes in ase-db?

Ask Hjorth Larsen asklarsen at gmail.com
Thu Mar 29 19:31:15 CEST 2018


Hi,

2018-03-23 17:28 GMT+01:00 John Kitchin via ase-users
<ase-users at listserv.fysik.dtu.dk>:
> Hi, I was trying to store a bytestring in an ase-db like this:
>
> ```
> import ase.db
> from ase import Atoms, Atom
> from ase.calculators.lj import LennardJones
>
> db = ase.db.connect('test.db')
>
> atoms = Atoms([Atom('Ar', [0, 0, 0])], cell=(10, 10, 10))
> atoms.set_calculator(LennardJones())
> atoms.get_potential_energy()
>
> db.write(atoms, data={'hash': b'1'})
> ```
>
> but it eads to this error
>
> TypeError: Object of type 'bytes' is not JSON serializable.
>
> It is not obvious to me why we shouldn't do (or be able to do) this. It also
> does not work as a keyword. Does anyone know a workaround?

A reasonable workaround is to save it as a unicode object, e.g.,
b'thehashvalue'.decode('ascii').

It would be reasonable to support bytes objects though.  This can be
done by modifying the ase.io.jsonio JSON-conversion function which
JSONizes numpy arrays outside of the normally JSONable objects.  Maybe
store it as a dictionary with explicit type, {'type': 'bytes',
'value': 'bytesasstring'}, if the 'type' key does not clash with
something else.

One could also automatically convert any bytes to strings with no
further ado, but then it cannot restore them as bytes which is
probably unacceptable.

Best regards
Ask

>
> John
>
> -----------------------------------
> Professor John Kitchin
> Doherty Hall A207F
> Department of Chemical Engineering
> Carnegie Mellon University
> Pittsburgh, PA 15213
> 412-268-7803
> @johnkitchin
> http://kitchingroup.cheme.cmu.edu
>
>
> _______________________________________________
> ase-users mailing list
> ase-users at listserv.fysik.dtu.dk
> https://listserv.fysik.dtu.dk/mailman/listinfo/ase-users


More information about the ase-users mailing list