<p dir="auto">Currently, json.Unmarshal (and json.Decoder.Decode) ignore fields in the incoming JSON which are absent in a target struct.</p>
<p dir="auto">For example, the JSON <code class="notranslate">{ "A": true, "B": 123 }</code> will successfully unmarshal into <code class="notranslate">struct { A bool }</code>.</p>
<p dir="auto">This makes it difficult to do strict JSON parsing. One place this is an issue is in API creation, since you want to reject unknown fields on incoming JSON requests to allow safe introduction of new fields in the future (I've had this use case previously when working on a JSON REST API). It also can lead to typos leading to bugs in production: when a field is almost always the zero value in incoming JSON, you might not realise you're not even reading a misspelled field.</p>
<p dir="auto">I propose that a new method is added to <code class="notranslate">Decoder</code> to turn on this stricter parsing, in much the same way <code class="notranslate">UseNumber</code> is used today. When in strict parsing mode, a key in the incoming JSON which cannot be applied to a struct will result in an <code class="notranslate">MissingFieldError</code> error. Like <code class="notranslate">UnmarshalTypeError</code>, decoding would continue for the remaining incoming data.</p>
<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="d := json.NewDecoder(r.Body)
d.UseStrictFields()
err := d.Decode(myStruct)"><pre class="notranslate"><code class="notranslate">d := json.NewDecoder(r.Body)
d.UseStrictFields()
err := d.Decode(myStruct)
</code></pre></div>
<ol dir="auto">
<li>What version of Go are you using? <code class="notranslate">5.3</code></li>
<li>What operating system and processor architecture are you using? <code class="notranslate">amd64,windows</code></li>
<li>What did you do?<br>
Read this: <a href="https://mailarchive.ietf.org/arch/msg/json/Ju-bwuRv-bq9IuOGzwqlV3aU9XE" rel="nofollow">https://mailarchive.ietf.org/arch/msg/json/Ju-bwuRv-bq9IuOGzwqlV3aU9XE</a></li>
<li>What did you expect to see?<br>
...</li>
<li>What did you see instead?<br>
...</li>
</ol>