json - 严格的 JSON 解析
问题描述
使用 Go 解析 JSON 时,如果值为 null 或缺失,是否可能会失败,而无需通过 if 语句检查每个字段?例如:
package main
import (
"encoding/json"
"fmt"
)
type Bird struct {
Species string `json:"birdType"`
Description string `json:"what it does"`
}
func main() {
birdJson := `{"birdType": "pigeon"}`
var bird Bird
json.Unmarshal([]byte(birdJson), &bird)
fmt.Println(bird)
}
我希望引发一个错误,因为"what it does"
未定义
解决方案
不,encoding/json.Unmarshal
如果目标结构具有源 json 不包含任何匹配对象键的字段,则不会返回错误。
推荐阅读
- css - 通过 gulp 运行时,我的 scss 没有被转换为 css
- c - 条件编译#if和#else(和其他)在c中的工作
- .net - Visual Studio 2017 中引用和依赖项之间的区别
- python - 在 while 循环中使用 Timeit 并增加输入大小
- php - 当脚本运行超过 30 分钟时,数据库中的 PHP 脚本更新记录
- laravel - 表单字段:姓名和电话未与 Paystack 中的请求一起传递
- python - 过滤具有另一个数据框的多个列值的数据框
- reactjs - ScrollView 和 Flexbox 的问题
- java - 如何找到合适的复选框定位器
- javascript - 在 JS 中模拟 API 调用