You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on Dec 15, 2025. It is now read-only.
Repository navigation
This repository was archived by the owner on Dec 15, 2025. It is now read-only.
The behavior of json.Unmarshal when encountering field type inconsistencies. #703
func TestJson(t *testing.T) {
type info struct {
Id int64 `json:"id"`
}
type test struct {
Result []info `json:"result"`
}
r := `{"result":[{"id":"1"},{"id":"2"}]}`
var res1 test
var res2 test
// use encoding/json
json2.Unmarshal([]byte(r), &res1)
// use json-iterator/go
jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal([]byte(r), &res2)
len1 := len(res1.Result) // 2
len2 := len(res2.Result) // 1
fmt.Println(len1, len2)
}
I want to know which handling behavior is more appropriate.
The appropriateness of the behavior depends on your specific use case and requirements:
Strict Type Checking (Standard encoding/json):
Pros: Ensures that the data conforms exactly to the expected types, which can prevent subtle bugs and data inconsistencies.
Cons: Requires the input data to be strictly formatted, which might not always be the case, especially when dealing with external APIs or user-generated content.
Lenient Type Conversion (json-iterator/go):
Pros: More flexible in handling input data, which can be useful when dealing with inconsistent or loosely typed JSON data.
Cons: May mask data issues and lead to unexpected behavior if the type conversion does not work as intended.
Activity
Michailovich commentedon Aug 2, 2024
The appropriateness of the behavior depends on your specific use case and requirements:
Strict Type Checking (Standard encoding/json):
Pros: Ensures that the data conforms exactly to the expected types, which can prevent subtle bugs and data inconsistencies.
Cons: Requires the input data to be strictly formatted, which might not always be the case, especially when dealing with external APIs or user-generated content.
Lenient Type Conversion (json-iterator/go):
Pros: More flexible in handling input data, which can be useful when dealing with inconsistent or loosely typed JSON data.
Cons: May mask data issues and lead to unexpected behavior if the type conversion does not work as intended.
hkb1990 commentedon Nov 14, 2024
Both
Unmarshalfunctions returnError. You should handle errors first. Otherwise results are unpredictable.ansionfor commentedon Jan 8, 2025
Thx guys