Golang json returns struct fields that do not need to be output

type Goods struct {
    IDAutoModel
    CategoryIDModel // 
    NameModel
    DescriptionModel      // 
    Stores        uint64         `json:"stores"`             // 
    MinScore      uint64         `json:"min_score"`          // 
    Weight        float64        `json:"weight"`             // 
    TimeAllModel
    Category GoodsCategory `json:"category,omitempty"`
}

when returning the Goods json list, you don"t want to output Category struct. How to delete struct

in struct

return json share a struct . Some APIs do not need Category , so they are empty struct

.

there are places where Category needs to be output, such as the item details page, and the item list page does not need to output Category

.

omitempty and - not at all

Jun.01,2021

it's OK for you to use omitempty, and then note:
Category GoodsCategory-> Category * GoodsCategory
because you give him a specific struct, so omitempty won't work. Change it to a pointer, and the default will be a nil,. At this time, omiempty will work


.

Struct values encode as JSON objects. Each exported struct field becomes a member of the object unless

  • the field's tag is "-", or
  • the field is empty and its tag specifies the "omitempty" option.

The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero. The object's default key string is the struct field name but can be specified in the struct field's tag value. The "json" key in the struct field's tag value is the key name, followed by an optional comma and options. Examples:

/ / Field is ignored by this package.
Field int json: "-"

/ / Field appears in JSON as key "myName".
Field int json: "myName"

/ / Field appears in JSON as key "myName" and
/ / the field is omitted from the object if its value is empty,
/ / as defined above.
Field int json: "myName,omitempty"

/ / Field appears in JSON as key "Field" (the default), but
/ / the field is skipped if empty.
/ / Note the leading comma.
Field int json: ", omitempty"
The "string" option signals that a field is stored as JSON inside a JSON-encoded string. It applies only to fields of string, floating point, integer, or boolean types. This extra level of encoding is sometimes used when communicating with JavaScript programs:

Int64String int64 json: ", string"
The key name will be used if it's a non-empty string consisting of only Unicode letters, digits, dollar signs, percent signs, hyphens, underscores and slashes.

GO official Json package


use tag json: "-"
or the first letter of the structure field is lowercase


GoodsCategory is an associated structure and cannot be used with omitempty unless it is changed to the pointer * GoodsCategory so that it works on the zero nil of the pointer.

Menu