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

Add Json binding option to use field names instead of local names #719

Closed
tefra opened this issue Nov 9, 2022 · 2 comments
Closed

Add Json binding option to use field names instead of local names #719

tefra opened this issue Nov 9, 2022 · 2 comments

Comments

@tefra
Copy link
Owner

tefra commented Nov 9, 2022

    Hello, is it possible to make this optional? I went to upgrade this dependency in a project that relies on the json output having different key names and afaict it's not possible to make it output `var.name` instead of `var.local_name` without just copying next_value and changing that yield.

Specifically here, https://github.com/tefra/xsdata/blob/v22.11/xsdata/formats/dataclass/serializers/json.py#L104

Originally posted by @delfick in #389 (comment)

@tefra
Copy link
Owner Author

tefra commented Dec 4, 2022

Hi @delfick iat that time I was using the json bindings for tests mostly, it doesn't make sense to add an option to override the qualified name. It's pretty easy to override the JsonSerializer to achieve this.

@tefra tefra closed this as completed Dec 4, 2022
@delfick
Copy link

delfick commented Dec 4, 2022

I did end up doing this but it feels hacky to me

# TODO: Hopefully future version of xsdata makes the key behaviour configurable
class ModifiedJsonSerializer(serializers.JsonSerializer):
    def next_value(self, obj: t.Any) -> t.Iterator[t.Tuple[str, t.Any]]:
        """
        Exactly the same as is in serializers.JsonSerializer accept we yield var.name
        instead of var.local_name
        https://github.com/tefra/xsdata/issues/389#issuecomment-1305216183
        """
        ignore_optionals = self.config.ignore_default_attributes

        for var in self.context.build(obj.__class__).get_all_vars():
            value = getattr(obj, var.name)
            if var.is_attribute and ignore_optionals and var.is_optional(value):
                continue

            yield var.name, self.convert(value, var)

and surely this is exactly the kind of thing the config class is for?

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

2 participants