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

Closed
Ccheers opened this issue Aug 9, 2022 · 1 comment
Closed

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

Ccheers opened this issue Aug 9, 2022 · 1 comment

Comments

@Ccheers
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 (
	"encoding/json"
	"log"
)

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)

	log.Println(a)
	// output &{5}

	log.Println(b)
	// 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
}

https://github.com/golang/go/blob/master/src/encoding/json/decode.go#L702

	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
				break
			}
		}
	}
@gopherbot gopherbot added this to the Proposal milestone Aug 9, 2022
@seankhliao
Copy link
Member

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.
Projects
None yet
Development

No branches or pull requests

3 participants