'Does the case of the JSON field name matter while doing Marshal and Unmarshal?
Are Marshal and Unmarshal functions strictly case sensitive?
The following structure defines a ticket:
type TicketInfo struct {
TicketKey string `json:"ticketKey"`
Ticketextnum string `json:"ticketextnum"`
TicketDate string `json:"ticketDate"`
TicketDesc string `json:"ticketDesc"`
}
This stringified form of this json will be passed as a single parameter in the payload of an API call by the source systems. What will happen if the source system sends, for example, "TicketKey" instead of "ticketKey" for the first field. Will json.Marshal correctly received the ticketKey field?
Solution 1:[1]
This is easily answered by reading the docs, or with a simple test. But specifically, see these notes (emphasis added) for Marshal:
Struct values encode as JSON objects. Each exported struct field becomes a member of the object, using the field name as the object key, unless the field is omitted for one of the reasons given below.
The encoding of each struct field can be customized by the format string stored under the "json" key in the struct field's tag. The format string gives the name of the field, possibly followed by a comma-separated list of options. The name may be empty in order to specify options without overriding the default field name.
and Unmarshal:
To unmarshal JSON into a struct, Unmarshal matches incoming object keys to the keys used by Marshal (either the struct field name or its tag), preferring an exact match but also accepting a case-insensitive match. By default, object keys which don't have a corresponding struct field are ignored (see Decoder.DisallowUnknownFields for an alternative).
So TL;DR; for marshaling, case is observed exactly, and for unmarshaling, exact case is preferred with a fallback to a case-insensitive match.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Community |
