Reputation: 13816
When encoding/decoding structs with json, almost all of the code out there use the same field name, but with the initial letter in lower case, why is this?
Since the names are the same, and json certainly can work with any case, why add this duplicate thing:
Name string `json:"name"`
Why not just use Name string
? It other case, adding the format string makes sense if the name is different than the go field name:
Name string `json:"MyName"`
Upvotes: 2
Views: 2137
Reputation: 79674
When encoding/decoding structs with json, almost all of the code out there use the same field name, but with the initial letter in lower case, why is this?
Because JavaScript traditionally/preferentially uses camelCase for variable and function names, so naturally JSON (originating in the JavaScript world) followed suit.
Of course this is not an enforce standard, and there are many competing standards. But since the question is why is this common, this seems the most likely answer.
You are, of course, free to use any casing system you want for JSON key names, and you most certainly will find examples of any casing system (including lack of system) in use in real software.
Upvotes: 1
Reputation: 121049
The encoding/json documentation says:
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.
Applications specify a lowercase name in the tag to produce a lowercase name in the JSON.
This struct
type Example struct {
Name1 string
Name2 string `json:"name1"`
}
encodes as:
{
"Name1": "1",
"name1": "2"
}
JSON only requires that field names be valid strings. Lowercase names are not required in JSON. That said, it is very common practice to start field names with a lowercase letter in JSON.
Upvotes: 5
Reputation: 552
Name string `json:"name" db:"SomeName"`
Keep in mind, string json:"name" db:"Name"
used to adjust de/serialization, can be in json or database.
for naming it depends on output. if database field is SomeName
so you must define db SomeName
.
So my questions goes to why almost all the applications want to use the lowercase?
if you encounter source code which using ouput json using only lowercase, this obviously to keep consistency output.
if lower case on variable give different effect too, for lower case act as private
variable and upper case act as public
variable so can be accessed through package.
Upvotes: 1