The problem

When used in json package, can the variables in the structure be converted to json fields without tag?

How to answer

  • If the variable starts with a lowercase letter, it is private. In any case, cannot turn, because can not get reflection information.

  • If the variable begins with a capital letter, it is public.

    • Do not add the tag, can be converted tojsonIn the field,jsonInner field name and structure body fieldFormerly known as consistent.
    • Added the tag, fromstructturnjsonThe time,jsonIs the name of the fieldtagIn the field name, the original field name is useless.

For example,

Deepen understanding with an example.

package main
import (
    "encoding/json"
    "fmt"
)
type J struct {  a string // No tag in lowercase  b string `json:"B"` / / lowercase + tag  C string // No tag in uppercase  D string `json:"DD"` / / capital + tag } func main(a) {  j := J {  a: "1". b: "2". C: "3". D: "4". }  fmt.Printf("Contents of j structure before json = %+v\n", j)  jsonInfo, _ := json.Marshal(j)  fmt.Printf("Json content = %+v\n".string(jsonInfo)) } Copy the code

The output

Json = {a:1 b:2 C:3 D:4}
Json content = {"C":"3"."DD":"4"}
Copy the code

explain

  • The structure defines four fields, one for eachLower case with no tag.Lowercase + tag.Capital has no tag.Capital + tag.
  • tojsonFirst letter.lowercaseWith or without the tagCan'ttojsonThe contents of theuppercaseaddedtagcanTake the alias, do not addtagthejsonField and structure fieldFormerly known as consistent.

Article recommendation:

  • Golang interview question: How to avoid memory escape?
  • Golang: What about memory escapes?
  • Golang Interview question: Does memory copy occur when a string is converted into a byte array?
  • Golang interview question: Flip containsChinese, numbers and English lettersThe string
  • Golang interview question: Is copying large slices more expensive than small slices?
  • Golang interview question: Can you tell the difference between uintptr and unsafe.pointer?
If you want to learn one thing every day?