marshmallow-jsonschema icon indicating copy to clipboard operation
marshmallow-jsonschema copied to clipboard

Support JSON schema for enums always loaded by name

Open pingsutw opened this issue 2 years ago • 5 comments

marshmallow_enum already supports load by value and load by name. https://github.com/justanr/marshmallow_enum

The goal I want is to dump my JsonScheam which has enum in it.

@dataclass_json
@dataclass
class Datum(object):
    x: Color

schema = Datum.schema()
JSONSchema().dump(schema)

Error message before change

    value = field_obj.serialize(attr_name, obj, accessor=self.get_attribute)
  File "/Users/kevin/opt/anaconda3/envs/flytekit-3.8/lib/python3.8/site-packages/marshmallow/fields.py", line 338, in serialize
    return self._serialize(value, attr, obj, **kwargs)
  File "/Users/kevin/opt/anaconda3/envs/flytekit-3.8/lib/python3.8/site-packages/marshmallow/fields.py", line 1864, in _serialize
    return self._serialize_method(obj)
  File "/Users/kevin/opt/anaconda3/envs/flytekit-3.8/lib/python3.8/site-packages/marshmallow_jsonschema/base.py", line 163, in get_properties
    schema = self._get_schema_for_field(obj, field)
  File "/Users/kevin/opt/anaconda3/envs/flytekit-3.8/lib/python3.8/site-packages/marshmallow_jsonschema/base.py", line 267, in _get_schema_for_field
    schema = self._from_python_type(obj, field, pytype)
  File "/Users/kevin/opt/anaconda3/envs/flytekit-3.8/lib/python3.8/site-packages/marshmallow_jsonschema/base.py", line 194, in _from_python_type
    json_schema["enum"] = self._get_enum_values(field)
  File "/Users/kevin/opt/anaconda3/envs/flytekit-3.8/lib/python3.8/site-packages/marshmallow_jsonschema/base.py", line 226, in _get_enum_values
    raise NotImplementedError(
NotImplementedError: Currently do not support JSON schema for enums loaded by value

pingsutw avatar Nov 14 '21 06:11 pingsutw

cc @fuhrysteve

pingsutw avatar Nov 14 '21 07:11 pingsutw

Am I misunderstanding this? This doesn't appear to actually load them by value, it just removes the error message and loads them by name. Could you please provide some test cases to illustrate this use-case?

fuhrysteve avatar Nov 15 '21 20:11 fuhrysteve

I want to dump JSON schema from my dataclass, I've updated the tests. I think the problem is that no matter what LoadDumpOptions is, we should always use load by name here.

pingsutw avatar Nov 16 '21 09:11 pingsutw

sorry, updated the title.

pingsutw avatar Nov 16 '21 09:11 pingsutw

Thanks for the PR! This looks great, I really appreciate your adding that test case!

Looks like the reason the build is failing is just because there's an extra indentation in one of the test cases that the black formatter doesn't like. If you're patient I'll get around to fixing it for you and merging this in - however if you beat me to it that'd be great too!

fuhrysteve avatar Dec 03 '21 00:12 fuhrysteve