Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Unmarshal struct case-sensitively

Is there any way to make json.Unmarshal not accept a case-insensitive match? I receive a JSON with tags such as "e" and "E" and would like to unmarshal the object with tag "e" but ignore the one with "E". Right now the only solution I found was to define a struct containing both tags and then to simply ignore tag "E", but I'm looking for a cleaner solution.

From the official doc:

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.

like image 316
Principled Avatar asked Feb 27 '18 10:02

Principled


People also ask

How do you Unmarshal a JSON?

To parse JSON, we use the Unmarshal() function in package encoding/json to unpack or decode the data from JSON to a struct. Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. Note: If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError.

Is Golang JSON case sensitive?

JSON is case sensitive to both field names and data. So is N1QL.

What is JSON Marshal Unmarshal?

Generally, encoding/decoding JSON refers to the process of actually reading/writing the character data to a string or binary form. Marshaling/Unmarshaling refers to the process of mapping JSON types from and to Go data types and primitives.


1 Answers

Unfortunately this is not something currently supported by the standard json library.

According to https://golang.org/pkg/encoding/json/#Unmarshal

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

There is no way to turn this behaviour off.

like image 184
Pandelis Avatar answered Oct 04 '22 19:10

Pandelis