proposal: encoding/json: add "Skip when Unmarshalling" tag #19423
Labels
Milestone
Comments
The "-" option already applies to both Marshal and Unmarshal. This new behavior is more like a one-way mirror. I don't think this pulls its weight as far as adding to the standard library: ignoring a field completely is common, but only wanting to include it in half the operations much less so, and it's already possible to get this behavior by defining your own type for the fixed field:
|
OK, thank you for the feedback and the code example - that answers my use case perfectly! |
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
I propose adding a new struct tag to the json/encoding package that tells the unmarshaller to skip a field when it is unmarshalling, and leave the existing value as-is.
This mirrors the behaviour the "-" option in the marshal operation.
An example use case of this is a RESTful API service that serves JSON data, and also accepts JSON data from clients to update the data. The endpoint is represented as a struct:
In this case the client might want to GET the endpoint, modify the data and then POST it directly back. However, if we unmarshal this directly into an Endpoint struct, the client could accidentally (or purposefully) overwrite our fixed field. ´To fix this, lets add a semantic to the struct tag to express that this field should be skipped by the unmarshaller:
I used the term "skip" here as an example, perhaps we can use some clearer terminology in the actual implementation.
In this trivial example it is simple to add some logic that ignores this field in the request handler. However, in larger structs it becomes clearer and less error-prone to have a declarative way to express that a value should not be modified by the unmarshalling process.
The text was updated successfully, but these errors were encountered: