← 中文资源

简体中文版本

JSON 键大小写不敏感匹配

encoding/json 匹配键时精确优先、大小写不敏感兜底:apikey 与 APIKEY 都能命中 APIKey 字段;匹配不上的键静默丢弃,需要严格拒绝时另开 DisallowUnknownFields。

阅读英文原文

实现说明

JSON 键大小写不敏感匹配以函数 main为骨架。

常见问题

「JSON 键大小写不敏感匹配」这个示例怎么运行?

直接执行即可——程序只依赖运行时自身。

核心语句

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

代码示例

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)
}