connorferster / forallpeople

Python SI units library: your 'daily driver' for calculations.
Apache License 2.0
272 stars 38 forks source link

[Feature request] Make quantity objects json serializable and deserializable #59

Open kishaningithub opened 2 years ago

kishaningithub commented 2 years ago

It would be great if SI quantities can be serialized and deserialized from a json string

Current behavior

import forallpeople as si
import json

>>> var = 1 * si.kg
>>> json.dumps(var)

Expected result

Value should be both json serializable and deserialisable

Actual result

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/homebrew/Cellar/python@3.9/3.9.13_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/opt/homebrew/Cellar/python@3.9/3.9.13_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/opt/homebrew/Cellar/python@3.9/3.9.13_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/opt/homebrew/Cellar/python@3.9/3.9.13_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Physical is not JSON serializable

Operating system

Mac OS X

kishaningithub commented 2 years ago

I am not sure if there is a specification on how to represent quantities in json

connorferster commented 2 years ago

We would have to create a JSON serialization specification. It's something that I am aware of and it would be nice to have .to_json() and Physical.from_json methods.