TRY AND ERROR

気になったこと、勉強したこと、その他雑記など色々メモしていきます。。Sometimes these posts will be written in English.,

Goでjsonのunmarshal結果を構造体に入れる時のフィールド名について

Goでjsonを扱う場合、json文字列をbyte配列にしたものをencoding/jsonパッケージのunmarshalに渡し、あらかじめ定義しておいた構造体に入れるといったのが定番ですが、その際に構造体のフィールド名を先頭を大文字にしていないとマッピングできないということに気づいた。。。
ちょっと気になったので公式ドキュメントを見てみると、exported(外部パッケージから参照できるというGoのスコープのことをいっている)の場合のみセットする仕様であることがちゃんと書かれていた。

When you need to handle json data, the most popular way to do that is using "unmarshal" method in the encoding/json package with the arguments that is byte encoded json and prepared structure. But in then, the structure's fields must be written as the first character upper case. (If it's not enough condition, "unmarshal" cannot mapping data into the structure.)
In the official Document, there's a sentence just like "Unmarshal will only set exported fields of the struct.".
"exported fields" means like "Possible to use in the other package".

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. Unmarshal will only set exported fields of the struct.

Details below.
json - The Go Programming Language