Home  >  Article  >  Backend Development  >  How to Achieve Case-Sensitive JSON Unmarshal in Go?

How to Achieve Case-Sensitive JSON Unmarshal in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-09 07:43:02476browse

How to Achieve Case-Sensitive JSON Unmarshal in Go?

Case-Sensitive JSON Unmarshal in Go

The json.Unmarshal function in Go provides a way to deserialize JSON data into a struct. By default, Unmarshal performs case-insensitive matching between the JSON keys and the struct field names or tags. However, there may be cases where it is desirable to have case-sensitive matching.

Problem

Suppose you receive JSON data with tags such as "e" and "E". You want to unmarshal the object with tag "e" and ignore the one with "E". With the default case-insensitive matching, Unmarshal will accept both tags and unmarshal the struct accordingly.

Solution

Unfortunately, the standard json library does not currently support case-sensitive matching for Unmarshal. According to the official documentation:

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.

Therefore, there is no way to disable case-insensitive matching using the standard json library.

The above is the detailed content of How to Achieve Case-Sensitive JSON Unmarshal in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn