Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Statham object -> json-serializable dict #82

Open
JohnEmhoff opened this issue Feb 1, 2021 · 2 comments
Open

Statham object -> json-serializable dict #82

JohnEmhoff opened this issue Feb 1, 2021 · 2 comments

Comments

@JohnEmhoff
Copy link

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.

@jacksmith15
Copy link
Owner

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))

@NfNitLoop
Copy link

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()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants