JSON Keys Match Case Insensitively

encoding/json matches keys exactly first and case-insensitively as a fallback, so apikey still fills APIKey; unmatched keys are dropped silently.

GoData Integrity

Code

gosnippet
28 lines
package main

import (
	"encoding/json"
	"fmt"
)

type Profile struct {
	UserName string `json:"user_name"` // tag 匹配是精确优先
	APIKey   string
}

func main() {
	// 无精确匹配时退回大小写不敏感:apikey 也能命中 APIKey 字段
	var p1 Profile
	fmt.Println(json.Unmarshal([]byte(`{"apikey":"k-1"}`), &p1), p1.APIKey)

	var p2 Profile
	fmt.Println(json.Unmarshal([]byte(`{"APIKEY":"k-2"}`), &p2), p2.APIKey)

	// 字段名本身也是候选:UserName 命中精确名,user_name 命中 tag
	var p3 Profile
	fmt.Println(json.Unmarshal([]byte(`{"UserName":"ada"}`), &p3), p3.UserName)

	// 匹配不上的键静默丢弃;要严格拒绝需另开 DisallowUnknownFields
	var p4 Profile
	fmt.Println(json.Unmarshal([]byte(`{"UserNameX":"typo"}`), &p4), p4)
}

How it works

JSON Keys Match Case Insensitively comes down to the function main.

Everything runs in main, which unmarshals four JSON payloads into Profile values. The struct has two fields: UserName carries a json:"user_name" tag, while APIKey has none. The first payload uses the key apikey and still fills APIKey with k-1, because when no exact match exists the decoder falls back to case-insensitive matching; the second uses APIKEY and fills APIKey with k-2 the same way. The third uses UserName, which hits the Go field name exactly and stores ada. The fourth uses UserNameX — a typo that matches nothing — so the printed struct stays zero-valued, and the comment notes that strictly rejecting unknown keys requires opting into DisallowUnknownFields.

Key statements

UserName string `json:"user_name"` // tag 匹配是精确优先

Interactive Tools for This Topic

FAQ

How do you run JSON Keys Match Case Insensitively?
Run the file on its own; every call resolves against the standard surface it already imports.