严格的JSON解析

huangapple go评论86阅读模式
英文:

Strict JSON parsing

问题

在使用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"未定义。

英文:

When parsing JSON with Go, is it possible to fail if a value is null or missing, without having to check every single field via an if statement?
For example:

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

I'd expect to raise an error since "what it does" is not defined

答案1

得分: 1

不,encoding/json.Unmarshal 如果目标结构体的字段在源 JSON 中没有匹配的对象键,将不会返回错误。

英文:

No, encoding/json.Unmarshal will not return an error if the target struct has fields for which the source json does not contain any matching object keys.

huangapple
  • 本文由 发表于 2021年8月26日 16:32:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/68935144.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定