Open JohnEmhoff opened 3 years ago
Its not something I've included yet, as the main focus is for parsing/validating incoming data that you don't control (there are better solutions for schema which you do control - pydantic
is a good example!).
I do see that this could be desirable even in that case however!
A statham Object
instance stores its attributes under _dict
. All of the other types are json-serialisable, so one could happily do the following:
import json
from statham.schema.elements import Object
class StathamEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Object):
return obj._dict
return super().default(self, obj)
class MyObject(Object):
foo: str
print(json.dumps(MyObject({"foo": "bar"}), cls=StathamEncoder))
Adding a vote here for better support for creating objects to match a JSON Schema.
I'm using JSON Schema to have a shared data type across languages. I'd like my Python code to be able to safely create objects of the right shape/type to then serialize for others to use. So if I have a required name
parameter, it would be nice if there were an initializer like:
data = Example.create(name="foo")
and maybe
data.validate()
data.to_json()
Is there a way to get a plain ol' python object (i.e., something I can give to
json.dumps
) if I have a statham object? Apologies if this should be obvious but the only thing I could find in the documentation is something about serializing the schema itself.