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

proposal: encoding/json: mark field when struct decoding #54351

Ccheers opened this issue Aug 9, 2022 · 1 comment

proposal: encoding/json: mark field when struct decoding #54351

Ccheers opened this issue Aug 9, 2022 · 1 comment


Copy link

Ccheers commented Aug 9, 2022

in this case the id field value is 5 , but the key "id" is match in better.

package main

import (

type Foo struct {
	ID uint `json:"id"`

const jsonStr = `{"id":2,"ID":5}`

func main() {
	a := &Foo{}
	b := make(map[string]interface{})
	json.Unmarshal([]byte(jsonStr), a)
	json.Unmarshal([]byte(jsonStr), &b)

	// output &{5}

	// output map[ID:5 id:2]

add a flag like "isMatched" when matched with nameIndex set the flag "true"

like this:

type structFields struct {
	list      []field
	nameIndex map[string]int

// A field represents a single field found in a struct.
type field struct {

        isMatched bool // add a flag when nameIndex matched

	if i, ok := fields.nameIndex[string(key)]; ok {
		// Found an exact name match.
		f = &fields.list[i]
+               f.isMatched = true
	} else {
		// Fall back to the expensive case-insensitive
		// linear search.
		for i := range fields.list {
			ff := &fields.list[i]
+			if !ff.isMatched && ff.equalFold(ff.nameBytes, key) {
				f = ff
@gopherbot gopherbot added this to the Proposal milestone Aug 9, 2022
Copy link

Duplicate of #14750

@seankhliao seankhliao marked this as a duplicate of #14750 Aug 9, 2022
@seankhliao seankhliao closed this as not planned Won't fix, can't repro, duplicate, stale Aug 9, 2022
@golang golang locked and limited conversation to collaborators Aug 9, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
None yet

No branches or pull requests

3 participants