首頁  >  文章  >  後端開發  >  Go 中的 json.Unmarshal 什麼時候回傳錯誤?

Go 中的 json.Unmarshal 什麼時候回傳錯誤?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-11-15 12:16:02801瀏覽

When Does json.Unmarshal in Go Return Errors?

JSON Decoding Errors in Go

When decoding JSON into structs using the json.Unmarshal function in Go, it's important to understand the circumstances under which an error will be returned.

When Errors Are Not Returned

Unlike some languages, the JSON decoder in Go does not report an error if values in the JSON source do not correspond to values in the target struct. For instance, it's not considered an error if the JSON contains a field that is not present in the struct.

When Errors Are Returned

However, json.Unmarshal will return errors in the following situations:

  • Syntax errors: If the JSON is malformed or contains invalid syntax, an error will be returned. The error message will provide details about the location of the error.
  • JSON value not representable by target type: If the value in the JSON cannot be converted to the corresponding type in the struct, an error will be returned. For example, if the JSON contains a boolean value but the struct field expects a string, json.Unmarshal will fail.

Example

Consider the following code:

type A struct {
  Name string `json:"name"`
}

jsonString := `{"status": false}`
var a A
err := json.Unmarshal([]byte(jsonString), &a)

In this example, json.Unmarshal will not return an error, even though the JSON does not contain the expected name field. The decoder will simply ignore the status field and leave the Name field of the A struct empty.

However, if the JSON contained the following:

{"name": false}

json.Unmarshal would return an error because the JSON value cannot be converted to a string type.

以上是Go 中的 json.Unmarshal 什麼時候回傳錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn