Go · Level 3 JSON

JSON and Struct Tags

Shape the JSON an API returns with Go struct tags: snake_case key names with json:"...", and omitempty for optional fields, but never on a value that can really be 0.

  • json.Marshal turns a struct into JSON
  • a tag sets the key name
  • omitempty also drops a real 0

json.Marshal turns a struct into JSON, and a tag like json:"price_cents" sets the key name. omitempty leaves out empty values: 0, "", false, nil, and empty slices and maps. Trap: omitempty also drops a real 0, so a free item would lose its price.

type User struct {
    Name  string `json:"name"`
    Email string `json:"email,omitempty"`
}
// {"name":"Ana"} when Email is ""

Add tags to Product so ToJSON gives {"id":1,"name":"Pen","price_cents":120,"discount":15}, leaving out discount when it is 0 but always keeping price_cents.

solution.go
Test Suites Pending
Output