JSON 处理
# JSON 处理
encoding/json 使用结构体标签定义字段名和省略规则,只有导出字段会参与编码。
type Result struct {
Target string `json:"target"`
Healthy bool `json:"healthy"`
}
decoder := json.NewDecoder(reader)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&result); err != nil {
return fmt.Errorf("decode result: %w", err)
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
内存中的单个值可用 json.Marshal,流式输入输出使用 Decoder 和 Encoder。外部请求应限制正文大小,并明确未知字段、时间格式、数字精度和 nil 切片编码规则。