Join GitHub today
GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.Sign up
proposal: encoding/json: add "Skip when Unmarshalling" tag #19423
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.
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 "-" 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: